0% found this document useful (0 votes)
29 views1 page

Shape Rectangle Triangle: // Main Function For The Program

This document discusses polymorphism in C++. It provides an example of a base Shape class with derived Rectangle and Triangle classes that override the area() method. When area() is called through a Shape pointer, it displays the base class output instead of the derived class output due to static resolution. Making area() virtual in the base class enables dynamic resolution, calling the correct overridden method at runtime based on the object type.

Uploaded by

daisyduck2013
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views1 page

Shape Rectangle Triangle: // Main Function For The Program

This document discusses polymorphism in C++. It provides an example of a base Shape class with derived Rectangle and Triangle classes that override the area() method. When area() is called through a Shape pointer, it displays the base class output instead of the derived class output due to static resolution. Making area() virtual in the base class enables dynamic resolution, calling the correct overridden method at runtime based on the object type.

Uploaded by

daisyduck2013
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

6/21/2021 Polymorphism in C++ - Tutorialspoint

cout << "Triangle class area :" <<endl;

return (width * height / 2);

};

// Main function for the program

int main() {

Shape *shape;

Rectangle rec(10,7);

Triangle tri(10,5);

// store the address of Rectangle

shape = &rec;

// call rectangle area.

shape->area();

// store the address of Triangle

shape = &tri;

// call triangle area.

shape->area();

return 0;

When the above code is compiled and executed, it produces the following result −

Parent class area :

Parent class area :

The reason for the incorrect output is that the call of the function area() is being set once by the
compiler as the version defined in the base class. This is called static resolution of the function
call, or static linkage - the function call is fixed before the program is executed. This is also
sometimes called early binding because the area() function is set during the compilation of the
program.
But now, let's make a slight modification in our program and precede the declaration of area() in the
Shape class with the keyword virtual so that it looks like this −

class Shape {

protected:

int width, height;

public:

https://www.tutorialspoint.com/cplusplus/cpp_polymorphism.htm 2/4

You might also like