WEB DEVELOPER SITE
PYTHONPHPJAVA
 

C++ Polymorphism



Polymorphism means that a single function can have a number of different implementations.

polymorphism occurs when there is a hierarchy of classes and they are related by inheritance.


you want to make a simple game, which includes different enemies: monsters, ninjas, etc.an attack function. However, they each attack in a different way. In this situation, polymorphism allows for calling the same attack function on different objects, but resulting in different behaviors.
create the Enemy class Polymorphism_1.JPG

second step to create Ninjas and Monsters. Both of these new classes inherit from the Enemy class, so each has an attack power. At the same time, each has a specific attack function.

Polymorphism_2.JPG
create our Ninja and Monster objects in main. We've now created two pointers of type Enemy, pointing them to the Ninja and Monster objects. Polymorphism_2.JPG

the pointer demonstrates, that you can use the Enemy pointer without actually knowing that it contains an object of the subclass