user9150170
user9150170

Reputation:

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?

Upvotes: 1

Views: 1797

Answers (2)

einpoklum
einpoklum

Reputation: 132260

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.

Upvotes: 3

Clearer
Clearer

Reputation: 2306

Use a base class with static variables:

#include <iostream>
struct C
{
    static int x;
    static int y;
};

struct A : C
{

};

struct B : C
{

};

int C::x = 0;
int C::y = 0;

int main()
{
    A a;
    a.x = 1;
    a.y = 2;
    B b;
    std::cout << b.x << b.y << '\n';
}

If you find yourself in a situation where you think you need to do this, please reconsider your design.

Upvotes: -1

Related Questions