Reputation: 1633
Class A{
public:
int a;
vector<A> test;
};
Class B{
public:
B();
B(const B &rhs);
~B();
B & insertTest(A element,A element1) {
element.test.pushback(element1); //doesn't work
}
B & insertTest1(A element) {
test1.pushback(element);//works
};
private:
vector<A> test1;
};
I'm trying to insert elements to these two vectors. It works when i insert element to vector test1 in class B. However, I can't get value after inserting to the vector in Class A.
Upvotes: 1
Views: 357
Reputation: 133008
The following doesn't work because element is passed by value
B & insertTest(A element,A element1) {
element.test.push_back(element1); //doesn't work
}
The following works since you are modifying test1, which is a member of this
B & insertTest1(A element) {
test1.push_back(element);//works
};
If you want the first to work, pass element by reference, like this:
B & insertTest(A& element,A element1) {
element.test.push_back(element1);
}
Upvotes: 1
Reputation: 92261
It sort of works in both cases, but as you pass element
by value to the function, you just insert the new element into this copy, not into the original.
The changes you make to the copy disappears as soon as you leave the function.
Upvotes: 4
Reputation: 49812
You pass the elements by value; you have to pass them by reference to make any visible changes. Also, why do you declare your functions as returning a reference to B
without actually returning anything? Apart from that, the syntax is totally wrong, and the code shouldn't even compile.
Upvotes: 2
Reputation: 91270
B & insertTest(A element,A element1); {element.test.pushback(element1);}
^
Remove that semicolon.
Also:
A & element, A & element1
insteadA
shouldn't really contain a vector of itself - what are you trying to do there?Upvotes: 3