Virtual Function in C++
Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call.
They are mainly used to achieve Runtime polymorphism
Functions are declared with a virtual keyword in base class.
The resolving of function call is done at Run-time.
Rules for Virtual Functions
Diagram Of Virtual Function
Virtual functions cannot be static.
A virtual function can be a friend function of another class.
Virtual functions should be accessed using pointer or reference of base class type to achieve run time polymorphism.
The prototype of virtual functions should be the same in the base as well as derived class.
They are always defined in the base class and overridden in a derived class. It is not mandatory for the derived class to override (or re-define the virtual function), in that case, the base class version of the function is used.
A class may have virtual destructor but it cannot have a virtual constructor.
Example Of virtual Function In C++
#include<iostream.h>
#include<conio.h>
class A
{
public:
virtual void display()
{
cout<<"Base class is invoked"<<endl;
}};
class B:public A
{
public:
void display()
{
cout"Derived Class is invoked"<<endl;
}};
void main()
{
A*a;//pointer of base class
B b;//object of derived class
a=&b;
a->display();//LateBinding occurs
getch();
}//End
Thanks For Viewing This Post Hope You Enjoyed.....!!!!
0 Comments