Sample Virtual Function in C++ Programming


A virtual function is a member function which is declared within a base class and is re-defined(Overriden) by a derived class. 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.

The program demonstrates the concept of virtual functions and polymorphism in C++ programming.

  • The program defines a base class vaccine with a virtual method putVaccine(). The putVaccine() method prints the message "Covid Vaccine".
  • Then it defines two derived classes, covaxin and covishield, which inherit from the vaccine base class and override the putVaccine() method to print their respective vaccine names.
  • In the main() function, objects cx and cs of classes covaxin and covishield are created, respectively.
  • A pointer o of type vaccine is created and assigned the address of cx. The putVaccine() method is called using the o pointer, which results in the derived class covaxin's putVaccine() method being called, printing the message "Put Covaxin Vaccine".
  • Then the o pointer is assigned the address of cs, and the putVaccine() method is called again, this time resulting in the derived class covishield's putVaccine() method being called, printing the message "Put Covishield Vaccine".

Source Code

//Virtual Function
#include<iostream>
using namespace std;
class vaccine
{
    public:
   virtual void putVaccine()
    {
        cout<<"Covid Vaccine"<<endl;
    }
};
class covaxin:public vaccine
{
    public:
    void putVaccine()
    {
        cout<<"Put Covaxin Vaccine"<<endl;
    }
};
class covishield:public vaccine
{
     public:
    void putVaccine()
    {
        cout<<"Put Covishield Vaccine"<<endl;
    }
};
int main()
{
   covaxin cx;
    covishield cs;
 
     vaccine *o=NULL;
     o=&cx;
     o->putVaccine();
     o=&cs;
     o->putVaccine();
    return 0;
}
 

Output

Put Covaxin Vaccine
Put Covishield Vaccine
To download raw file Click Here

Program List


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