Suppose we have 3 classes Button
, Clickable
and Rectangle
.
Neither of them are abstract and can exist on their own. All of them have a position
member variable. When the Button
class inherits from Clickable
and Rectangle
they should share a common position
variable.
My implementation:
struct Positionable {
struct Position {
int x, y;
} position;
};
struct Rectangle: virtual public Positionable {
// ...
};
struct Clickable : virtual public Positionable {
// ...
};
struct Button : virtual public Positionable, public Rectangle, public Clickable {
Button() {
this->position.x = 1;
assert(Rectangle::position.x == 1);
assert(Clickable::position.x == 1);
assert(Positionable::position.x == 1);
}
} test;
The problem with this (besides the 3 forms of the word position) is that I feel, that I'm breaking the composition over inheritance principle, because I inherit only to include a variable.
Is there a design pattern with the same behavior? How can I use composition in this situation?
EDIT:
I'm looking for a solution where the Button
inherits from Clickable
and from Rectangle
, because it's an is-a relationship. (It might not be the best example, but assume that it's true)
I also don't want to inherit from Positionable
, because it's a has-a relationship.
And I want the same behavior like my implementation, so:
- All of them have a
Position position
- When they inherit from each other, they share this variable
- I don't use setters/getters
Basically I want something like virtual variables, but c++ doesn't have that feature yet, so I'm looking for a sensible replacement.