Search code examples
c++classcopy-constructormember-variables

Copy an object and make both share a member variable (C++)


I have been thinking and searching this but I can't solve this question. I would like an object that when copied into another object, both objects share certain member variable. So, when I change the value of the member variable of object1, it's also changes the variable in object2. Example:

class ABC {
public:
    int a = 5;
    //...
}

int main() {
    ABC object1;

    ABC object2 = object1;

    object2.a = 7;      // now, object1.a is equal to 7
    object1.a = 10;     // now, object2.a is equal to 10
}

I know about copy constructors, but I am not sure if it applies here or there is a better method. I have been thinking about using pointers or references, but can't make the trick. Note that I don't want all the objects to share the same variable.


Solution

  • What you need is a pointer. The pointer points to the object and then all objects that copy the first one just copy the pointer so that they all point to the same thing. To make life easy we can use a std::shared_ptr to manage the allocation and deallocation for us. Something like:

    #include <memory>
    
    class Foo
    {
    private:
        std::shared_ptr<int> bar;
    public:
        Foo() : bar(std::make_shared<int>()) {}
        int& getBar() { return *bar; }
    };
    
    int main()
    {
        Foo a;
        a.getBar() = 7;
        Foo b = a;
        b.getBar() = 10;
        // now getBar returns 10 for both a and b
        Foo c;
        // a and b are both 10 and c is 0 since it wasn't a copy and is it's own instance
        b = c;
        // now b and c are both 0 and a is still 10
    }