Virtual Function Example in C++


Description:

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.

Example Program:

Here is the simple program virtual function in C++.

Source Code

#include<iostream>
using namespace std;
class Parent
{
public:
    virtual void display()
    {
        cout<<"Display Parent"<<endl;
    }
};
class Child:public Parent
{
public :
    void display()
    {
        cout<<"Display Child"<<endl;
    }
};
int main()
{
    Parent *o =new Child();
    o->display();
    return 0;
}
To download raw file Click Here

Output

Display Child


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