Search code examples
c++classpointerspass-by-reference

How do I create a class variable that can affect the object passed through the constructor?


So I have class A, which has an object of class B as a class variable. I constructed an object of class B in the main (objB) , and use class A's constructor to pass objB into class A (and assigned it to class variable called objC of type B).

How can I make it so whenever I call objC.do() it can change the original objB as well?


Solution

  • Instead of having a B member, use a reference as a member:

    class A {
        B& the_b;
        // etc.
    public:
        A(B& some_b) : the_B { some_B } { }
    }