C++

Runtime Polymorphism: Virtual Functions in C++

This guide will explain virtual functions and explain their use. All subclasses that override a function that is declared virtual in a class have their function implementations set to virtual by default (whether they mark them virtual or not). Why is a function declared virtual? To inform the compiler that the call to this function needs to be resolved at runtime (also known as late binding and dynamic linking) in order for the right version of the function to be called and the object type to be determined.

To further understand what occurs when we don’t designate an overridden function as virtual, let’s look at an example.

Example 1: Replacing a function that isn’t virtual

See the problem here. Even though we have the parent class pointer pointing to the instance (object) of child class, the parent class version of the function is invoked.

You may be thinking why I have created the pointer, I could have simply created the object of child class like this: Dog obj; and assigned the Dog instance to it. Well, in this example I have only one child class but when we a big project having several child classes, creating the object of child class separately is not recommended as it increases the complexity and the code become error prone. More clarity to this after this example.

#include<iostream>
using namespace std;
//Parent class or super class or base class
class Animal{
public:
   void animalSound(){
      cout<<"This is a generic Function";
   }
};
//child class or sub class or derived class
class Dog : public Animal{
public:
   void animalSound(){ 
      cout<<"Woof";
   }
};
int main(){
   Animal *obj;
   obj = new Dog();
   obj->animalSound();
   return 0;
}

Output:

This is a generic Function

Example 2: Implementing Virtual Function

As you can see, the result in this situation is Woof, as we would anticipate. What occurs in this scenario? The call to animalSound() is resolved at runtime because we designated the function as virtual. The compiler ascertains the object’s type at runtime and calls the appropriate method.

#include<iostream>
using namespace std;
//Parent class or super class or base class
class Animal{
public:
   virtual void animalSound(){
      cout<<"This is a generic Function";
   }
};
//child class or sub class or derived class
class Dog : public Animal{
public:
   void animalSound(){ 
      cout<<"Woof";
   }
};
int main(){
   Animal *obj;
   obj = new Dog();
   obj->animalSound();
   return 0;
}

Output:

Woof

Related Articles

Leave a Reply

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

Back to top button