Program To Illustrate Pointer To Derived Class Objects 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


In the above program ptr is a pointer variable of the base class and d1 and d2 are the objects of derived classes derv1 and derv2 respectively.The statement

ptr = &d1;

assigns the address of the derived class object d1 to the base class pointer ptr.The statement

ptr -> display ( );

invokes the member function display ( ) using the base class pointer ptr.One would expect that since the base class pointer contains the address of derived class object d1 , it should invoke derv1’s member function display ( ).But actually the base class display ( ) member function is invoked.This is because corresponding to this function call , static binding is performed depending upon the type of pointer variable and not its contents.This makes sense as the pointer variable does not get the address of any object untill runtime.

Similar is the case when we invoke the display ( ) using the pointer ptr containing address of object d2 of derv2 class.

OUTPUT

Base class display called

Base class display called