A function is extensible if it’s being defined as virtual in the base class. When a derived class inherits from a base class, that means both classes may refer to either derived class type or base class type. Under such circumstances, how are you going to tell the compiler which class type you are referring to during run-time? Well, by declaring a virtual function in the base class will solve the problem. When the function prototype is preceded with the keyword virtual in the base class then the derived class’s function would be called. Otherwise, the base class’s function would be called. Let’s take a look at the following sample source code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Base class
class Animal
{
public:
  void Identity()
  {
    printf("i am an Animal\n");
  }
};

// Derived class - Bird
class Bird : public Animal
{
public:
  void Identity()
  {
    printf("i am a Bird\n");
  }
};

// Derived class - Dog
class Dog : public Animal
{
public:
  void Identity()
  {
    printf("i am a Dog\n");
  }
};

// Main function
int _tmain(int argc, _TCHAR* argv[])
{
  Animal * animal = new Bird();
  animal->Identity();  // print Bird's identity

  animal = new Dog();
  animal->Identity();  // print Dog's identity

  return 0;
}
Problem: If you try to compile the code and run it now, you will see the output as shown below. C++ Virtual Function This is not the desired output. The compiler assumed that animal is an Animal object (base class type). Therefore, the base class object is being called instead of the derived class object.
Solution: By declaring the Identity as a virtual function in the base class will solve the problem. Just adding a virtual keyword and that’s all you need to do.
1
2
3
4
5
6
7
8
9
// Base class
class Animal
{
public:
  virtual void Identity()
  {
    printf("i am an Animal\n");
  }
};
If you compile the code and run it now, you will see the output as shown below. C++ Virtual Function This time it will display the desired output. All derived class’s identity function were called and displayed accordingly. The virtual keyword in the base class will inform the compiler to where it should get the reference pointer for each derived classes. Download sample source code: C++ Virtual Function Example