Whats in this post?
- Background and Explanation of the code
To copy code: Click “View Source” on the right of this code snippet.
Background and Explanation of the code
In main ( ), we declare pointer ptr of shape class and create an object r1 of derive class rectangle.The user inputs the length and breadth of r1 object.The address of r1 object is assigned to the base class pointer (ptr).The statement
ptr -> cal_area ( );
on execution invokes the cal_area ( ) function of the derive class rectangle as ptr contains the address of r1 object.
Similarly the same function call which occurs in the later part of the program results in execution of cal_area ( ) function corresponding to derive class triangle as ptr now contains the address of triangle’s object (t1).
Enter length and breadth of rectangle : 20 30
Area of rectangle = 600
Enter base and perpendicular of triangle : 10 30
Area of triangle = 150