Polymorphism refers to the property by which objects belonging to different classes can respond to the same message in various forms. When there are C++ functions with the same name in both the superclass and the subclass, the virtual function allows the programmer to call a member function of a different class by the same function call, depending on the context. This feature is known as polymorphism, one of the essential features of OOP. The pointer is also one of the critical aspects of C++ language similar to that of C. In this tutorial, you will learn about virtual functions in C++.



What is Virtual Function in C++?

A virtual function is a form of a member function declared within a base class and redefined by a derived class. The keyword virtual is used to create a virtual function, preceding the function's declaration in the base class. If a class includes a virtual function and gets inherited, the virtual class redefines a virtual function to go with its own need. In other words, a virtual function is a function that gets overridden in the derived class and instructs the C++ compiler to execute late binding on that function. A function call is resolved at runtime in late binding, so the compiler determines the object type at runtime.

Program for Virtual Function

Example:

#include 
using namespace std; 

class b
{
public:
    virtual void show()
    {
        cout<<"\n  Showing base class....";
    }
    void display()
    {
        cout<<"\n  Displaying base class...." ;
    }
};

class d:public b
{
public:
    void display()
    {
        cout<<"\n  Displaying derived class....";
    }
    void show()
    {
        cout<<"\n  Showing derived class....";
    }
};

int main()
{
    b B;
    b *ptr;
    cout<<"\n\t P points to base:\n" ; ptr=&B; ptr->display();
    ptr->show();
    cout<<"\n\n\t P points to drive:\n"; d D; ptr=&D; ptr->display();
    ptr->show();
}

Program Output:

     P points to base:

Displaying base class....
Showing base class....
   
     P points to drive:
      
Displaying base class....
Showing derived class....


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram