Shape Rectangle Triangle: // Main Function For The Program
Shape Rectangle Triangle: // Main Function For The Program
};
int main() {
Shape *shape;
Rectangle rec(10,7);
Triangle tri(10,5);
shape = &rec;
shape->area();
shape = &tri;
shape->area();
return 0;
When the above code is compiled and executed, it produces the following result −
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:
public:
https://www.tutorialspoint.com/cplusplus/cpp_polymorphism.htm 2/4