Run time Polymorphism
Virtual functions
In C++ polymorphism indicates the form of a member function that can be changed at runtime. Such member functions are called virtual function and the corresponding classes are called polymorphic class.
The object of the polymorphic class, addressed by pointers changes at runtime and respond differently for the same message. Such a mechanism requires postponement of binding of a function call to the member function (declared as virtual) until runtime.
Virtual means existing in appearance but not in reality. When virtual functions are used, a program that appears to be calling a function of one class may in reality be calling a function of a different class.
Example:1
There are three (3) classes A , B and C. All three classes have the member function with the same name display().
Sol:
#include<iostream> #include<conio.h> using namespace std; class A { public: void display() { cout<<"Display function of class A"<<endl; } }; class B { public: void display() { cout<<"Display function of class B"<<endl; } }; class C { public: void display() { cout<<"Display function of class C"<<endl; } }; int main() { // normal object and pointer variable are decalred A a1,*a2; B b1,*b2; C c1,*c2; //linking the pointer to the object // i.e. putting the address of object into pointer object // when member function of a class is called using a normal // object dot (.) operator is used // whereas //when member function is called using a pointer type //object // arrow( ->) is used. a2=&a1; a2->display(); b2=&b1; b2->display(); c2=&c1; c2->display(); getch(); return(0); }
Output:
Display function of class A
Display function of class B
Display function of class C
In the above example, Static binding / early binding is performed as the binding of the function to the function called is decided before the execution of the program.
In early/static binding the linking of the function to be called is done before the execution of the program.