virual function code example

Example: virual function

#include 
using namespace std;

class Enemy {
public:
	virtual void Attack() {}
};

class Ninja : public Enemy 
{
public:
	void Attack() {
		cout << "ninja attack" << endl;
	}
};

class Monster :public Enemy 
{
	void Attack() {
		cout << "Monster attack" << endl;
	}
};

int main() {
	Ninja ninjaObj;
	Monster monsterObj;

	Enemy* ninjaPointer = &ninjaObj;
	Enemy* monsterPointer = &monsterObj;

	ninjaPointer->Attack();
	monsterPointer->Attack();
}


/*A virtual function is a member function that you expect to be redefined in derived classes. 
When you refer to a derived class object using a pointer or a reference to the base class,
you can call a virtual function for that object and execute the derived class's version of the function.*/

Tags:

Misc Example