on 2 comments

C++ Virtual Functions and Runtime Polymorphism

Virtual Function

Virtual function is a function of base class that is overrided in derived class and this function binds at run time. To define a function as virtual function, virtual keyword is used. Virtual function is defined in base class, when it is expected to redefine this function in derived class. 

The functions those are virtual in base class, also virtual in derived class.

If you want to declare a function as virtual function, then the function declaration needs virtual keyword, not the function definition.  

Virtual keyword tells the compiler to perform late binding on this function.

Example of Virtual Function

#include<iostream>
using namespace std;
class Base
{
public:
    virtual void display()
    {
        cout<<"\nI am in base class\n";
    }
};
class Derived: public Base
{
public:
    void display()
    {
        cout<<"\nI am in derived class\n";
    }
};
int main()
{
    Base B, *ptr;
    Derived D;
    B.display();
    D.display();

    cout<<"\nNow base class pointer containing the address of base class object";
    ptr = &B;
    ptr->display();

    cout<<"\nNow base class pointer containing the address of derived class object";
    ptr = &D;
    ptr->display();     //Line 32
    return 0;
}

OUTPUT:

I am in base class

I am in derived class

Now base class pointer containing the address of base class object
I am in base class

Now base class pointer containing the address of derived class object
I am in derived class


If the display() function is not defined with virtual keyword in base class, then the statement of line 32 calls the display() function of base class. This is because of early binding.

In early binding, compiler decides which function to call according to the type of pointer ptr at compile time. At compile time compiler does not checks which address pointer ptr is containing. This is because, at compile time memory is not allocated.

Virtual function tells the compiler to perform late binding on that function.

In late binding functions are called according to the address of pointer ptr in above example.




2 comments:

  1. Hi Bharat! Great blog so far, I am a C++ developer as you, I created a cool tool for C++ developers, can I offer you a free license for this tool in exchange for a small article/review of this tool on your blog? If so, drop me a mail please to Artem dot Razin you-know-what gmail dot com :) Happy coding!

    ReplyDelete