Skip to content

Virtual Functions in C++

Reading Time: < 1 minute

Virtual functions in c++ is ,if you want to execute the member function of derived class then, you can declare  a function  in the base class virtual which makes that function existing in appearance only but, you can’t call that function. In order to make a function virtual, you have to add keyword virtual in front of a function.

{code type=c++}
#include 
using namespace std;
class B
{
    public:
     virtual void display()      /* Virtual function */
         { cout<<"Content of base class.\n"; }
};

class D1 : public B
{
    public:
       void display()
         { cout<<"Content of first derived class.\n"; }
};

class D2 : public B
{
    public:
       void display()
         { cout<display();  // You cannot use this code here because the function of base class is virtual. */

    b = &d1;
    b->display();   /* calls display() of class derived D1 */
    b = &d2;           
    b->display();   /* calls display() of class derived D2 */
    return 0;
}
{/code}
Output:
Content of first derived class.
Content of second derived class.

A Class with pure virtual function is called a abstract class.A class is made virtual only when there is no need to define its definition in base class 
itself.Virtual methods can be used only in interface design.It allows us to create a list of base class pointers.Virtual functions can also be known as polymorphism.The return type of virtual function and it's override must match.
If the return type of a virtual function is a pointer or a reference to a class, override functions can return a pointer or a reference to a derived class. These are called covariant return types.

See also  Redirect to History - Yii

Leave a Reply