I have 3 classes A
, B
and C
, declared as
class A {
int varA;
};
class B {
int varB;
};
class C : public A, public B {
void setVar(int var) {
varA = var;
varB = var; // <- duplicate
}
};
Now class C
will have 2 variables varA
and varB
. In my case, both variables have the same meaning (eg. position of a physical object) and thus always need to be the same, since member functions will only do calculations on their own variable.
I thought about adding a parent class for A
and B
, but then the same problem persists:
class Parent {
public:
int var;
};
class A : public Parent {};
class B : public Parent {};
class C : public A, public B {
void setVar(int v) {
A::var = v;
B::var = v; // <- duplicate
// or
var = v; // <- compiler error: Ambiguous call
}
};
Does anyone know an elegant solution to this problem?
Edit: Context
Classes A
and B
are Physics
and Collidable
respectively. The class Physics
enables an object to have variables like acceleration, speed and position. And consists a couple of member functions to calculate the next position based on the time elapsed. The other class Collidable
enables an object to interact (collide) with other objects, defining their behavior when a collision occurs while also checking whether they are in fact colliding or not. This class has variables such as position and a bounding box.
The overlapping variable is thus the position since both classes need it independently from each other. The class Collidable
does not need to inherit from Physics
because a wall for example does not need variables like acceleration and/or speed since it's static.
I wanted to use inheritance for C
because that will be an object that is-a physics object and is-a collidable object. A has-a relation does not seem appropriate, hence I chose inheritance over composition.