Virtual Function

on

A Virtual Function is a member function that you expect to be redefined in derived class. In simple words, virtual keyword is used to make member function of the base class, which is overrides in the derived class, also called Late Binding/ Dynamic Binding/ Runtime Polymorphism

Without Virtual Keyword

#include<iostream>
using namespace std;

class Base
{
public:
    void show(){
        cout<<"Base - Show Function ";
    }
};

class Derived :public Base
{
public:
    void show()
    {
        cout<<"Derived- Show Function";
    }


};
int main()
{
    Derived d;
    Base *b;
    b= &d;
    b->show();  // early binding occurs

    return 0;
}	

Output:
Base – Show Function

With Virtual Keyword

#include<iostream>
using namespace std;

class Base
{
public:
    virtual void show(){
        cout<<"Base - Show Function ";
    }
};

class Derived :public Base
{
public:
    void show()
    {
        cout<<"Derived- Show Function";
    }


};
int main()
{
    Derived d;
    Base *b;
    b= &d;
    b->show();  // late binding

    return 0;
}

Output:
Derived – Show Function

Accessing Virtual private method of derived class:

#include<iostream>
using namespace std;

class Base
{
public:
    virtual void show(){
        cout<<"Base - Show Function ";
    }
};

class Derived :public Base
{
private:
    void show()
    {
        cout<<"Derived- Show Function";
    }


};
int main()
{
    Derived d;
    Base *b;
    b= &d;
    b->show();

    return 0;
}
Output:

Derived – Show Function

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s