Saturday, 19 December 2015

Understanding virtual function in CPP

A function declared with keyword virtual is called virtual function. Virtual functions are handy when classes are Polymorphic i.e when child class and parent classes have functions with same name.
Let's understand the problem when we don't use virtual function.

#include<iostream>
using namespace std;
class Parent{
public:
void showMe(){
cout<<"\nParent is showing!";
}
};

class Child: public Parent{
public:
void showMe(){
cout<<"\nChild is showing!";
}
};

int main(){
Parent *parentPointer;
parentPointer = new Parent();
parentPointer->showMe();//its calling Parent->showMe()//

parentPointer = new Child();
parentPointer->showMe(); //it is also calling Parent->showMe()//
return 0;
}

Output:
Parent is showing!
Parent is showing!

When we don't declare Parent class function as a virtual, compiler does early binding which means for all the direct function references compiler will replace the reference with actual address of the method.
Now let's declare the Parent class function as a virtual

#include<iostream>
using namespace std;
class Parent{
public:
virtual void showMe(){
cout<<"\nParent is showing!";
}
};

class Child: public Parent{
public:
void showMe(){
cout<<"\nChild is showing!";
}
};

int main(){
Parent *parentPointer;
parentPointer = new Parent();
parentPointer->showMe();//it is calling Parent->showMe()//

parentPointer = new Child();
parentPointer->showMe(); //Now it is calling Child->showMe()//
return 0;
}

Output:
Parent is showing!
Child is showing!

When we declare the base class function as virtual, the function call using a Parent reference, as in shown in second example, compiler does not know which method will get called at run time. In this case compiler will replace the reference with code to get the address of function at run-time.

Why do we need to use Parent class pointer, cant we just declare Child class pointer itself and call the respective function instead declaring  virtual function?

Valid question, but consider a scenario when we have a Parent class Animal and Children classes Dog, Cat, Rat, Fox etc, each one has one common function says():
Now we have a function which demonstrates how individual animal sounds which will accept Parent class point because it has to access each of it's child class function;

void animalSound(Animal *pointer){
    pointer->says();
}

If we want animalSound function to call the child class function, we need delay the binding of early binding by declaring Animal class says() function as virtual.




No comments:

Post a Comment