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.
  1. #include <iostream>
  2. using namespace std;
  3. class Weapon
  4. {
  5. public:
  6. void loadFeatures()
  7. { cout << "Loading weapon features.\n"; }
  8. };
  9. class Bomb : public Weapon
  10. {
  11. public:
  12. void loadFeatures()
  13. { cout << "Loading bomb features.\n"; }
  14. };
  15. class Gun : public Weapon
  16. {
  17. public:
  18. void loadFeatures()
  19. { cout << "Loading gun features.\n"; }
  20. };
  21. int main()
  22. {
  23. Weapon *w = new Weapon;
  24. Bomb *b = new Bomb;
  25. Gun *g = new Gun;
  26. w->loadFeatures();
  27. b->loadFeatures();
  28. g->loadFeatures();
  29. return 0;
  30. }
Output
Loading weapon features.
Loading bomb features.
Loading gun features.
We defined three pointer objects wb and g of classes WeaponBomb 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.
  1. class Loader
  2. {
  3. public:
  4. void loadFeatures(Weapon *weapon)
  5. {
  6. weapon->features();
  7. }
  8. };
The loadFeatures() loads the feature of a specific weapon.

Let's try to implement our Loader class

  1. #include <iostream>
  2. using namespace std;
  3. class Weapon
  4. {
  5. public:
  6. Weapon() { cout << "Loading weapon features.\n"; }
  7.   void features()
  8. { cout << "Loading weapon features.\n"; }
  9. };
  10. class Bomb : public Weapon
  11. {
  12. public:
  13. void features()
  14. {
  15.   this->Weapon::features();
  16.   cout << "Loading bomb features.\n";
  17. }
  18. };
  19. class Gun : public Weapon
  20. {
  21. public:
  22. void features()
  23. {
  24.   this->Weapon::features();
  25.   cout << "Loading gun features.\n";
  26.   }
  27. };
  28. class Loader
  29. {
  30. public:
  31. void loadFeatures(Weapon *weapon)
  32. {
  33. weapon->features();
  34. }
  35. };
  36. int main()
  37. {
  38. Loader *l = new Loader;
  39. Weapon *w;
  40. Bomb b;
  41. Gun g;
  42. w = &b;
  43. l->loadFeatures(w);
  44. w = &g;
  45. l->loadF
Output
Loading weapon features.
Loading weapon features. 
Loading weapon features.
Loading weapon features. 


Comments

Popular posts from this blog

C++ Templates ?

C++ Program to Print Number Entered by User

Educational Website