0

I'm trying to get this function to create a new object but I can't get it working.

Main.cpp:

BaseUnit MyUnits;
vector<BaseUnit> Units;
MyUnits.CreateNewUnit(Units);

BaseUnit.cpp:

BaseUnit::BaseUnit(int ID)
{
    UnitID = ID;
}

..Other code...

void BaseUnit::CreateNewUnit(vector<BaseUnit> MyVector)
{
    UnitID++;
    BaseUnit NewUnit(UnitID);
    MyVector.push_back(NewUnit);

}

I don't know how to get it to return back into the Vector of object in the main code.

3
  • 2
    CreateNewUnit operates on a copy. Commented Apr 11, 2015 at 11:34
  • You may see here how to use a vector as return type. For your case you'll need a reference parameter: void BaseUnit::CreateNewUnit(vector<BaseUnit>& MyVector) Commented Apr 11, 2015 at 11:35
  • To make your code easier to understand for others, consider to adhere to established naming conventions. For C++ that means that only types, macros and constants should start with uppercase letters. Commented Apr 11, 2015 at 12:01

1 Answer 1

1

To return the modified vector

vector<BaseUnit> BaseUnit::CreateNewUnit(vector<BaseUnit> MyVector) // note the return type
{
    UnitID++;
    BaseUnit NewUnit(UnitID);
    MyVector.push_back(NewUnit);
    return MyVector; // simple as that
}

You can then use this function to update the original vector:

Units = MyUnits.CreateNewUnit(Units);

However, this will modify a copy of the vector and then change the variable Units to refer to that new vector (in C++11) or even create another copy of it and assign that (in C++98), which both isn't very efficient. To instead directly modify the passed vector in your function, pass it as reference like πάντα ῥεῖ suggested in the comments:

void BaseUnit::CreateNewUnit(vector<BaseUnit>& MyVector) // note the '&'
{
    UnitID++;
    BaseUnit NewUnit(UnitID);
    MyVector.push_back(NewUnit); // this will now modify the original vector
}

Use this with

MyUnits.CreateNewUnit(Units);

as you had in your original code.

Sign up to request clarification or add additional context in comments.

2 Comments

"However, this will modify a copy of the vector and then change the variable Units to refer to that new vector" That's only in C++11; in C++ versions before C++11, there will be a second copy made in the assignment of Units. Note that g++ (and possibly other compilers) still defaults to older C++ versions.
Good catch, @celtschk, I wasn't aware of that. I've edited my answer to reflect that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.