Reputation: 305
I have 3 classes MovableObject
, FixedObject
and CollisionObject
. A CollisionObject
should have the possibility to be either a MovableObject
or a FixedObject
. But it would make no sense to use multiple inheritance, as it can't be both at the same time. Basically, if I create a Projectile
, the hierarchy would be:
Sprite <- MovableObject <- CollisionObject <- Projectile
And if I create an Obstacle
it would be:
Sprite <- FixedObject <- CollisionObject <- Obstacle
(My base class is Sprite
)
So what CollisionObject
should inherit from is decided by what the child objects inherits from (Either a Movable-
or FixedObject
). But how do I implement this in C++ in a nice way?
Upvotes: 0
Views: 47
Reputation: 20993
If CollisionObject is a class, then it will always inherit from the same classes, so what you request is not possible if you do not want to use multiple inheritance. But multiple inheritance would make CollisionObject both movable and fixed, which does not sound very right.
However, if you make CollisionObject a template, it can be done:
template<typename Base> class CollisionObject : public Base
{
...
};
class Projectile : public CollisionObject<MovableObject> {...};
class Obstacle : public CollisionObject<FixedObject> {...};
Upvotes: 2
Reputation: 63124
Disclaimer: the usefulness of this answer will vary wildly depending on the rest of your design.
That said, "A CollisionObject
should have the possibility to be either a MovableObject
or a FixedObject
" does not sound like you need a CollisionObject
to somehow switch its base class, but instead to be the base class.
struct CollisionObject { };
struct MovableObject : CollisionObject { };
struct FixedObject : CollisionObject { };
Upvotes: 2