Load features weapon program example using Virtual Function in C++


Example Program:

Here is the simple program for printing the weapon program using Virtual Function in C++.

Source Code Example : 1

#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->loadFeatures(w);
  return 0;
}
To download raw file Click Here

Output

Loading weapon features.
Loading weapon features.
Loading weapon features.
Loading weapon features.

Source Code Example : 2

#include<iostream>
using namespace std;
class Weapon
{
  public:
  void loadFeatures()
  {
    cout<<"Loading weapon features.\n";
  }
};

class Bomb : public Weapon
{
  public:
  void loadFeatures()
  {
    cout<<"\n Loading bomb features.\n";
  }
};

class Gun : public Weapon
{
  public:
  void loadFeatures()
  {
    cout<<"\n 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;
}
To download raw file Click Here

Output

Loading weapon features.
Loading bomb features.
Loading gun features.


Basic Programs


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples



Learn All in Tamil © Designed & Developed By Tutor Joes