I have been reading about inheritance vs composition. I know there is already allot about this topic on this site, but i have a question about this specific example I hope will not be seen as duplicate.
Some guidelines I have gathered so far:
- Prefer composition over inheritance.
- Has-a relationship will therefore almost always mean composition.
- Is-a relationship CAN mean inheritance is best, but not always.
So now for the example
I have been working on a simple game engine to practice C++. For this I have made some classes:
- The Image class that contains an image that can be rendered.
- The Transform class is all about positioning.
- The Sprite class contains an image that can be rendered, in a specific position.
There is more of course, but let’s keep it simple for the example.
So - Sprite HAS an image and HAS a position (transform). Following the guideline that would mean composition for both. BUT I think it is just so much easier to have Sprite inherit from Transform.
Because I what to do things sprite->setPosition() and sprite ->setScale().
If a Sprite inherits from Transform, I don’t have to do anything, sprite->setPosition() automatically calls Transform::setPosition() for the sprite object.
If Sprite HAS a Transform, I would have to redirect ALL of these kind of methods to the Transform! (It's how I have been doing it so far and it seems to work fine) I don’t want to write things like this for every positioning method: (there are quite a few already)
Sprite::setPosition(Vector2 position) { mTransform.setPosition(Vector2 position); }
But It seems to go against convention. What do you all think?