Inheritance and polymorphism are both very useful and really show off the power of object-oriented programming. However, in some circumstances, inheritance can cause more problems than it solves, and therefore, we should bear in mind a few rules of thumb when deciding whether or not to use it.
Let's say we want to make a more powerful Enemy
object; it will have the same behavior a regular Enemy
object will have but with more health. One possible solution would be to derive a new class PowerEnemy
from Enemy
and give it double health. In this solution the new class will seem extremely sparse; it will use the functionality from Enemy
but with one different value. An easier solution would be to have a way to set the health of an Enemy
class, whether through an accessor or in the constructor. Inheritance isn't needed at all.
When deriving a class, it is a good idea for it to model the "is a" relationship. This means that the derived class should also be of the same type as the parent class. For example, deriving a Player2
class from Player
would fit the model, as Player2
"is a" Player
. But let's say, for example, we have a Jetpack
class and we derive Player
from this class to give it access to all the functionality that a Jetpack
class has. This would not model the "is a" relationship, as a Player
class is not a Jetpack
class. It makes a lot more sense to say a Player
class has a Jetpack
class, and therefore, a Player
class should have a member variable of type Jetpack
with no inheritance; this is known as containment.
On platforms such as PC and Mac, the performance penalties of using inheritance and virtual functions are negligible. However, if you are developing for less powerful devices such as handheld consoles, phones, or embedded systems, this is something that you should take into account. If your core loop involves calling a virtual function many times per second, the performance penalties can add up.
3.141.200.3