I'm having difficulties explaining the problem with words. But I have replicated my problem in a minimal example. Basically I have a main class holding a vector of a different class objects. This main class has a member function that creates an object, add it to the vector, and returns a pointer to the new object in the vector. When I then try to access the values of the object from the pointer that was returned, the values are as if they were never set.
Here is the code of a minimal example:
EDIT:
As some pointed out I had value = value in the member function. This was obviously a mistake, and I've edited to _value = value
#include <iostream>
#include <vector>
class MySecondaryClass
{
public:
MySecondaryClass(int aValue) { _aValue = aValue; }
~MySecondaryClass() {}
int _aValue;
};
class MyMainClass
{
private:
std::vector<MySecondaryClass> _secClassVec;
public:
MyMainClass() {}
~MyMainClass(){}
MySecondaryClass* addNewSecClass(int aValue) {
MySecondaryClass newSecClass(aValue);
_secClassVec.push_back(newSecClass);
return &_secClassVec[_secClassVec.size() - 1];
}
};
int main() {
MyMainClass mainObject;
MySecondaryClass* secObject1_ptr = mainObject.addNewSecClass(1);
MySecondaryClass* secObject2_ptr = mainObject.addNewSecClass(2);
MySecondaryClass* secObject3_ptr = mainObject.addNewSecClass(3);
std::cout << secObject1_ptr->_aValue << std::endl;
std::cout << secObject2_ptr->_aValue << std::endl;
std::cout << secObject3_ptr->_aValue << std::endl;
return 0;
}
And the output:
-572662307
-572662307
3
Expected output is:
1
2
3
Can someone explain what I'm doing wrong here?