This tutorial will actually be a continuation of the topics covered in the last tutorial of Virtual Functions but this will be a fuller explanation of what virtual functions are and how they can be used in a program. We will present a simple database program with a virtual function to show how it can be used, then we will go on to illustrate a more complex use of the virtual function in a manner that finally illustrates its utility and reason for existence.
So what is a Virtual Function?
A Virtual function is a function which is declared in base class using the keyword virtual. We write the body of virtual function in the derived classes. Its purpose is to tell the compiler that what function we would like to call on the basis of the object of derived class. C++ determines which function to call at run time on the type of object pointer to.
Declaration of a virtual function
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 42 43 44 45 46 | class BaseClass{ public: virtual void who(void) { cout << "Base\n"; } }; class Derived1 : public BaseClass { public: void who (void) { cout << "Derived Class 1 \n"; } }; class Derived2 : public BaseClass { public: void who (void) { cout << "Derived Class 2\n"; } }; int main(void) { BaseClass b; BaseClass *bp; Derived1 d1; Derived2 d2; bp = &b; bp ->who(); //Executes the base class who function bp = &d1; bp ->who(); //Executes the Derived1 class who function bp = &d2; bp ->who(); //Executes the Derived2 class who function } //Out put //Base //Derived Class 1 //Derived Class 2 |