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.

  • Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call.
  • They are mainly used to achieve Runtime polymorphism
  • Functions are declared with a virtual keyword in base class.
  • The resolving of function call is done at Run-time.

The program defines a base class Base with a virtual method fun(), which prints the message "Function of Base Class".

  • Then it defines a derived class Derived, which inherits from the Base class and overrides the fun() method to print the message "Function of Derived Class".
  • In the main() function, an object o of class Derived is created. Then a pointer p of type Base is created and assigned the address of o.
  • When the fun() method is called using the p pointer, the derived class Derived's fun() method is called, demonstrating the concept of virtual functions.
  • Note that the commented-out lines in main() demonstrate an alternate way to call the methods directly on the object o of class Derived.

Source Code

#include<iostream>
using namespace std;
//Virtual Function in C++ Programming
 
/*
virtual Function is function is declared in base class and redefined in derived class.
Ability for the runtime polymorphism
*/
class Base
{
  public:
    virtual void fun()
    {
        cout<<"Function of Base Class"<<endl;
    }
};
 
class Derived:public Base
{
    public:
    void fun()
    {
        cout<<"Function of Derived Class"<<endl;
    }
};
int main()
{
    /*Derived o;
     o.fun();*/
      Derived o;
      Base *p=&o;
         p->fun();
    return 0;
}
 

Output

Function of Derived Class
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