Program Illustrates Use Of Pure Virtual Function In Calculating Area Of Rectangle And Triangle In C++

LEVEL: Beginner

Whats in this post?

  1. Code
  2. Output
  3. Background and Explanation of the 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 the function cal_area ( ) is declared as pure virtual function in the base class shape by using the following declaration

virtual void cal_area ( ) = 0;

This function is redefined in the derived class rectangle and triangle for calculating the area of particular shape.As there is no implementation provided for pure virtual function cal_area ( ), the compiler does not allow you to create an object of class shape .If the programmer attempts to make its object, the compiler generates an error message.

In the main ( ), the statement

shape *ptr [2]; creates an array of pointers to base class shape that can store the address of objects of the derived classes rectangle and triangle.After inputting the dimensions of two different types of shapes , we assign the address of r1 object to first pointer variable (ptr [0]) and the address of t1 object to second pointer variable (ptr [1]).

The statement

for (int i = 0; i < 2; i++)

ptr [i] -> cal_area ( );

invokes different versions of cal_area ( ) function using the same function call depending upon the object to which current pointer  ptr [i] is pointing. If the pointer in ptr points to a r1 object then cal_area ( ) function of rectangle class is invoked and if the pointer in ptr points to t1 object then cal_area ( ) function of triangle class is invoked .Thus, same function call invokes different functions and hence polymorphism is achieved.


Enter length and breadth of rectangle  :  10    20

Enter base and perpendicular of triangle  :   5     20

Area of rectangle  =  200

Area of triangle =   50