1
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.

rtn
  • 127,556
  • 20
  • 111
  • 121
thetux4
  • 1,583
  • 10
  • 25
  • 38

4 Answers4

4

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.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
3
B & insertTest(A element,A element1); {element.test.pushback(element1);}
                                    ^

Remove that semicolon.

Also:

  • You're modifying copies, since you pass by value - Pass A & element, A & element1 instead
  • Class A shouldn't really contain a vector of itself - what are you trying to do there?
  • You didn't post your real code
Erik
  • 88,732
  • 13
  • 198
  • 189
2

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.

Philipp
  • 48,066
  • 12
  • 84
  • 109
  • I wrote the syntax wrongly in here, but the code compiles. I just gave the relevant parts. – thetux4 May 08 '11 at 09:34
  • @thetux4: When you post code, post the *exact compilable code* that contains your problem. – Erik May 08 '11 at 09:36
1

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);
      }
rtn
  • 127,556
  • 20
  • 111
  • 121