C++ Virtual function

C++ Virtual Function:


#include
using namespace std;


class Father
{
public:
virtual void show()
{
cout << "Controls in Father class";
}
};


class Child:public Father
{
public:
void show()
{
cout << "Controls in Child Class";
}
};


int main()
{
Child d;
Father* b;       
b = &d;
b->show();     
}


OUTPUT:
Controls in Child Class


To understand above program first we should know, what is virtual function?
A function which is already declared in parent(base) class and is redefined in child(derived) class.
Here a pointer of parent class when refer to the object of child class, will execute the function of child class on calling the function of parent class.


As shown in above program.


Look this code,


Child d;
Father* b;       
b = &d;
b->show();     


  • Object d of Child class created.
  • Pointer b of Father class created.
  • Pointer b refer to the address of object d
  • Point b calls the function show(), which execute child class function.

Now the question is what is the use of Virtual function, if all above work can be performed without use of it?
So ans is virtual function is helps to achieve the run-time polymorphism  and virtual function ensure that correct function is called.


So what are the rules for Virtual Functions?
  • A class may have virtual destructor but it can’t have a virtual constructor.
  • Must be declared in public section of class.
  • Can’t be static.
  • Can’t be a friend function of another class.
  • It should be accessed using pointer or reference of parent class type to achieve runtime polymorphism.
  • The prototype of virtual functions should be same in parent as well as child class.
  • They are always defined in parent class and overridden in child class.

Related topics

Professor Jayesh video tutorial

Please use contact page in this website if you find anything incorrect or you want to share more information about the topic discussed above.