Featured Post

Trie implementation in C

Virtual Functions Explained

Virtual function is the probably most sought after feature of Object Oriented Programming practice.
Let me explain how it works.

Consider a case where a function called speak() is used in the base class Animals.
Now we derive a class like Dog from the base class and using a base's pointer try to call a derived overridden function, Here's what happens

#include <iostream>
using namespace std;

class Animals{

  public :

    virtual void speak(){
      cout<<"Animals speak random";
    }
};

class Dog: public Animals{

  public:
    
    void speak(){
      cout<<"Dogs woof";
    }
};

int main()
{
  Animals *a;
  Dog d;

  a = &d;

  a->speak();
}

Output:

//without virtual speak()

Animals speak random

//with virtual speak()

Dog woof



The Base class speak() function is called.

But if we add a virtual keyword in front of speak() , we would be able to access the derived class's function speak().

So Virtual Functions resolve to the most derived class's function which is overridden.

So user can have different functionality in Derived class for the same function using the virtual keyword.

Whenever a class declares a virtual function or is derived directly or indirectly from a class which declares a
virtual function, the compiler adds an extra hidden member variable which points to the virtual table. A virtual table is nothing but an array of pointers to the virtual functions. The entries in the virtual table are changed at run time to point to the correct function.

This is called Dynamic Binding where the resolution happens at runtime .

There is another variant of virtual function and that is a Pure Virtual Function . The only difference between the two being that a Pure Virtual Function needs the implementation to be done compulsorily in the derived classes too otherwise it'll throw a compiler error.And it does not let the base class do the implementation also.

#include <iostream>

using namespace std;

class Animals{

  public :

    void speak() = 0; //pure virtual function
    
};

class Dog: public Animals{

  public:
    
    void speak(){
      cout<<"Dogs woof";
    }
};

int main()
{
  Animals *a;
  Dog d;

  a = &d;

  a->speak();
}

Points to remember regarding virtual functions :

- Never call a virtual functions inside a constructor or a destructor

- There is no such thing called virtual constructor

Comments