This may be a stupid question, but what is the best way to program 2 classes that share a set of variables?
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?
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.