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.

mpromonet
  • 11,326
  • 43
  • 62
  • 91
TRV
  • 41
  • 6
  • 2
    `CreateNewUnit` operates on a copy. – milleniumbug Apr 11 '15 at 11:34
  • You may [see here](http://stackoverflow.com/questions/22655059/why-it-is-ok-to-return-vector-from-function/22655120?s=32|1.3072#22655120) how to use a vector as return type. For your case you'll need a reference parameter: `void BaseUnit::CreateNewUnit(vector& MyVector)` – πάντα ῥεῖ Apr 11 '15 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. – das-g Apr 11 '15 at 12:01

1 Answers1

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.

das-g
  • 9,718
  • 4
  • 38
  • 80
  • 1
    "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. – celtschk Apr 11 '15 at 12:56
  • Good catch, @celtschk, I wasn't aware of that. I've edited my answer to reflect that. – das-g Apr 11 '15 at 13:00