Cpp Tutorial: Dynamic or Runtime Polymorphism or Virtual Functions in C++

In this tutorial we shall learn about below topics
1. Need for virtual function
2. Virtual function example
3. Rules for a function to be virtual

1. Need for virtual function

Consider below example.
#include<iostream>

using namespace std;

class A{
public: 
        void show(){
        cout << " Hello from Class A";
    }
};

class B :public A{
public:
     void show(){
        cout << " Hello from Class B";
    }
};


int main(){

    A *a1 = new B; // Create a base class pointer and assign address of derived object.
    a1->show();

}
Concentrate on the line:
    A *a1 = new B;
    a1->show();

Here we are assigning Derived class object to Base class pointer. Then when you call “show()”. We expect that it will print “Hello from Class B”.

But the output will be “Hello from Class A”.

Because, here the binding will occur at compile time. Hence we need to move the binding at runtime. Hence we shall use virtual function.

2. Virtual function example

So when you make a function as virtual, it will become virtual in all the derived class.
“virtual” is the keyword used to make a function as virtual.
Below is an example for virtual function:
#include<iostream>

using namespace std;

class A{
public:
    virtual void show(){
        cout << " Hello from Class A";
    }
};

class B :public A{
public:
    void show(){
        cout << " Hello from Class B";
    }
};


int main(){

    A *a1 = new B;
    a1->show();

}
Output:
Hello from Class B.
6

3. Rules for a function to be virtual

1. A function that is virtual cannot be a static function or a friend function.
2. Virtual should be declared in base class.
3. The function should be defined in base and derived class.
4. We can only access virtual function with the help of pointer or reference.
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *