Virtual Functions in C++

Virtual Functions in C++

A virtual function is a member function that is declared within a base class and again defined by a derived class and it is declared with the virtual keyword. Run time polymorphism is achieved in C++ using virtual functions. When a class containing a virtual function is inherited, the derived class again defined the virtual function of their own need.

Rules of virtual Functions

  • Virtual functions are members of some classes and they cannot be static members.
  • Virtual function accessed through object pointers and must be defined in the parent class, even though it is not used

Program of Virtual Function in C++

#include <iostream>    
{    
 public:    
 virtual void display()    
 {    
  cout << "Parent class is invoked"<<endl;    
 }    
};    
class B:public A    
{    
 public:    
 void display()    
 {    
  cout << "Child Class is invoked"<<endl;    
 }    
};    
int main()    
{    
 A* a;      
 B b;         
 a = &b;    
 a->display();    
}    

Output

Child Class is invoked  

 

Read more, Friend Function in C++

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *