Answers for "virual function"

C++
0

virual function

#include <iostream>
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.*/
Posted by: Guest on May-04-2021

Browse Popular Code Answers by Language