Reputation: 19
I have a vector as a member of a class "B". It has its set and get functions:
setVector(vector<A*>)
getVector()
I am interested in filling this vector from another function that uses an object of this class "B". So I created new objects of class "A" and I did the following to update the vector member variable of the class "B" by mistake:
A* obj = new A;
B b;
B.getVector().push_back(obj);
What happened is that push_back did not work. In other words when I try to see the member variable using a debugger I see that the vector member variable still has a capacity of 0 as if I did not push_back anything to it.
I tried changing my implementation to be:
vector<A*> tempVector;
B b;
A* obj = new A;
tempVector.push_back(obj);
b.setVector(tempVector);
And it worked as expected.
I wanted to understand why that first behavior was a mistake? As I understand the constructor of class B should create a vector by default. So when I use the getVector() function it should return that created vector to me and then I can push_back to it. So I wanted to know what did I get wrong in this situation?
Upvotes: 0
Views: 1638
Reputation: 11340
The signature of getVector()
is probably something like std::vector<A*> getVector()
. This will return a copy of the actual vector. Then you push_back
to the copied vector, but never modify the member variable. You want to return a reference:
std::vector<A*> &getVector();
const std::vector<A*> &getVector() const;
Upvotes: 0
Reputation: 2642
The problem is probably the return type of getVector()
. Assuming it is defined as vector<A*> getVector()
, it returns the vector by value, which means that you did the push_back
on a copy of the vector, but not on the actual vector member.
If you want to be able to modify the vector from outside the class, all you have to do is change the function signature to pass it by reference instead: vector<A*>& getVector()
. This will make sure the modifications (such as push_back
) happen on the member variable.
Upvotes: 2