Program That Implements Run Time Polymorphism Using Virtual Function In C++

LEVEL: Beginner

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the code

Code


To copy code: Click View Source “View Source” on the right of this code snippet.


Background and Explanation of the code


The output of this program reveals that the member function display ( ) of the derived classes are invoked and not that of base class as expected.By defining the member function display ( ) as virtual in the base class,

virtual void display ( )

every call to this function through the base class pointer (ptr) will be dynamically bound(run time) and not at compile time.So if the base class pointer ptr contains the address of the object d1 of the derv1 class, then the statement

ptr -> display ( );

invokes the member function defined in the derived class derv1.The compiler chooses the appropriate member function of derived class derv1 at run time depending upon the contents of base class pointer and not the type of pointer.Here the compiler does not perform static binding as addresses of the derived class objects are not known to the base class pointer at compile time which are available only at run time .Hence binding decision is postponed until run time.

Similarly if the base class pointer ptr contain the address of object d2 of derv2 class then the statement ptr -> display ( ); invoked the display ( ) function defined in the derv2 class.

OUTPUT

Derv1’s display called

Derv2’s display called