c++class-designclass-hierarchyshared-data

C++ Design: How do I set up two classes that share a set of variables?


This may be a stupid question, but what is the best way to program 2 classes that share a set of variables?

  1. Class A and Class B both need access to int x and int y.
  2. If class A changes x or y, the changes should be reflected in class B

My thoughts: Class A and B can inherit Class C (which contains the variables x,y) - But this would create an instance of c for both A,B. - I only need one instance of x and y

Maybe I need friend class, or static variables?


Solution

  • First of all - it depends. You've not told us the whole story. But you've already made some assumptions I want to discourage you from making.

    The fact that A and B share some common data does not mean that they are inherently the same. A person may have a travel destination and a conference may have a venue, but that doesn't mean they need to be subclasses of the same thing.

    So it could very well be the case that the following is what you should use:

    struct C { int x; int y; };
    
    class A { 
        C& foo;
        int bar;
        A(C& some_c) : foo(some_c) { }
        // ... etc. ...
    };
    
    class B { 
        C& baz;
        int qux;
        A(C& some_c) : baz(some_c) { }
        // ... etc. ...
    };
    

    with no inheritance, no friend classes, no static variables - none of that stuff. And it may be the case that inheritance is appropriate; again, it depends.

    Note: The example I gave does not address potential divergence in scope/lifetime of A, B and C variables. If there is such divergence, it may make sense to create all of these objects on the heap and have A and B hold std::shared_ptr's to a C.