what is virtual function in c++
what is a virtual function in c++
A virtual function is a member function in base class that you expect to redefine in derived classes.
Before going into detail, let's build an intuition on why virtual functions are needed in the first place.
An Example to Begin With
Let us assume, we are working on a game (weapons specifically).
We created the Weapon class and derived two classes Bomb and Gun to load features of respective weapons.
#include <iostream>
using namespace std;
class Weapon
{
public:
void loadFeatures()
{ cout << "Loading weapon features.\n"; }
};
class Bomb : public Weapon
{
public:
void loadFeatures()
{ cout << "Loading bomb features.\n"; }
};
class Gun : public Weapon
{
public:
void loadFeatures()
{ cout << "Loading gun features.\n"; }
};
int main()
{
Weapon *w = new Weapon;
Bomb *b = new Bomb;
Gun *g = new Gun;
w->loadFeatures();
b->loadFeatures();
g->loadFeatures();
return 0;
}
Output
Loading weapon features. Loading bomb features. Loading gun features.
We defined three pointer objects w, b and g of classes Weapon, Bomb and Gun respectively. And, we called
loadFeatures()
member function of each objects using:w->loadFeatures(); b->loadFeatures(); g->loadFeatures();
Works perfectly!
However, our game project started getting bigger and bigger. And, we decided to create a separate Loader class to load weapon features.
This Loader class loads additional features of a weapon depending on which weapon is selected.
class Loader
{
public:
void loadFeatures(Weapon *weapon)
{
weapon->features();
}
};
The
loadFeatures()
loads the feature of a specific weapon.Let's try to implement our Loader class
#include <iostream>
using namespace std;
class Weapon
{
public:
- Weapon() { cout << "Loading weapon features.\n"; }
void features()
{ cout << "Loading weapon features.\n"; }
};
class Bomb : public Weapon
{
public:
void features()
{
this->Weapon::features();
cout << "Loading bomb features.\n";
}
};
class Gun : public Weapon
{
public:
void features()
{
this->Weapon::features();
cout << "Loading gun features.\n";
}
};
class Loader
{
public:
void loadFeatures(Weapon *weapon)
{
weapon->features();
}
};
int main()
{
Loader *l = new Loader;
Weapon *w;
Bomb b;
Gun g;
w = &b;
l->loadFeatures(w);
w = &g;
l->loadF
OutputLoading weapon features. Loading weapon features. Loading weapon features. Loading weapon features.
Comments
Post a Comment