thetux4
thetux4

Reputation: 1633

Inserting element into vector from different classes

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

Answers (4)

ralphtheninja
ralphtheninja

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

Bo Persson
Bo Persson

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

Philipp
Philipp

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

Erik
Erik

Reputation: 91270

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

Upvotes: 3

Related Questions