Using polymorphism to reuse code
Polymorphism means having several forms. Typically, we use polymorphism when there is a hierarchy of classes and they are related in some way. We generally achieve this level of relation by using inheritance.
Getting ready
You need to have a working copy of Visual Studio installed on your Windows machine.
How to do it…
In this recipe, we will see how we can use the same function and override it with different functionalities based on our needs. Also, we will see how we can share values across base and derived classes:
Open Visual Studio.
Create a new C++ project.
Select Win32 Console Application.
Add a source file called Source.cpp and three header files called
Enemy.h
,Dragon.h
, andSoldier.h
.Add the following lines of code to
Enemy.h
:#ifndef _ENEMY_H #define _ENEMY_H #include <iostream> using namespace std; class CEnemy { protected: int m_ihealth,m_iarmourValue; public: CEnemy(int ihealth, int iarmourValue) : m_ihealth(ihealth), m_iarmourValue(iarmourValue...