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; } |
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.
1 2 3 4 5 6 7 8 9 | // Base class class Animal { public: virtual void Identity() { printf("i am an Animal\n"); } }; |
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
C++ Virtual Function