#Why aren't both modified? What should I do to modify them both?

16 messages · Page 1 of 1 (latest)

wispy sentinel
#

Do I need pointers to the objects?

class B
{
    private:
        int x;
    public:
        B() {};
        B(int a)
{x = a;}
        ~B() {}
        int size() {
          return x;
}
        void add() {
   x++;
}
};
class A
{
    private:
        B b;
    public:
        A() {}
        ~A() {}
        A(B b2){
        this->b = b2;
            }
        int size(){
   return b.size();
}
};

int main()
{
    B b(3);
    A a(b);
    b.add();
    cout << b.size() << endl; //4
    cout << a.size() << endl; //3
}
flat gullBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

flat gullBOT
#

Do I need pointers to the objects?


class B {
 private:
  int x;

 public:
  B(){};
  B(int a) { x = a; }
  ~B() {}
  int size() { return x; }
  void add() { x++; }
};
class A {
 private:
  B b;

 public:
  A() {}
  ~A() {}
  A(B b2) { this->b = b2; }
  int size() { return b.size(); }
};

int main() {
  B b(3);
  A a(b);
  b.add();
  cout << b.size() << endl;  // 4
  cout << a.size() << endl;  // 3
}

browngoose2002
fair depot
#

You don't need to define a destructor that does nothing

#

A(B b2) { this->b = b2; } is taking an instance of B by value and copying it

#

Take a look at references

wispy sentinel
fair depot
#

Correct

#

A(B& b2) { this->b = b2; } is still copying whatever b2 refers to

wispy sentinel
fair depot
#

You need to make data member b in A a reference too

#

And then you'll need to use a member initializer list to bind the reference

wispy sentinel
fair depot
#

Happy to help

flat gullBOT
#

@wispy sentinel Has your question been resolved? If so, run !solved :)