C++ Polymorphism

Polymorphic literally means multiple forms. Polymorphism is used when there is a hierarchy between classes and the classes are inherited through inheritance.

C++ Polymorphism means that when a member function is called, different functions are executed depending on the type of the object that called the function.

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.

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

Virtual function

virtual functions are functions declared in the base class using the keyword virtual. When you redefine a virtual function defined in a base class in a derived class, you tell the compiler not to statically link to the function.

What we want is that any function in the program can choose to call the function according to the type of object being called. This operation is called dynamic link, or late binding.

Pure virtual function

You may want to define a virtual function in the base class so that the function is redefined in the derived class to better apply to the object, but you can't give a meaningful implementation of the virtual function in the base class. The pure virtual function will be used.