What is Virtual Function


What is Virtual Function

What is Virtual Function?

A virtual function is a member function within the base class that we redefine in a derived class. It is declared using the virtual keyword. When a class containing virtual function is inherited, the derived class redefines the virtual function to suit its own needs. The compiler performs late binding on this function. To make a function virtual, we write the keyword virtual before the function definition.

#include<iostream.h>
class Animals
{
   public:
   virtual void sound()
   {
     cout << "this is parent class" << endl;
   }
};
class Dogs : public Animals
{
      public:
      void sound()
     {
       cout << "Dogs bark" << endl;
      }
};

int main()
{
   Animals *a;
   Dogs d;
   a= &d;
   a -> sound();
   return 0;
}


Rules for Virtual Function in C++:

• They are always defined in a base class and overridden in derived class but it is not mandatory to override in the derived class.
• The virtual functions must be declared in the public section of the class.
• They cannot be static or friend function also cannot be the virtual function of another class.
• The virtual functions should be accessed using a pointer to achieve run time polymorphism.

Post a Comment

0 Comments