In this tutorial, I will explain about the Polymorphism concept in cplusplus. Polymorphism is the advanced concept of OOP (Object Oriented Programming).
The word Polymorphism stand for having many forms. Typically, Polymorphism used in case of inheritance within a class or different class.
Below program will explain the concept of Polymorphism and at the end of this tutorial, we have shared the output of the below c++ program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | #include <iostream> using namespace std; class Shape { protected: int width, height; public: Shape( int a = 0, int b = 0){ width = a; height = b; } int area() { cout << "Parent class area :" <<endl; return 0; } }; class Rectangle: public Shape { public: Rectangle( int a = 0, int b = 0):Shape(a, b) { } int area () { cout << "Rectangle class area :" <<endl; return (width * height); } }; class Triangle: public Shape { public: Triangle( int a = 0, int b = 0):Shape(a, b) { } int area () { cout << "Triangle class area :" <<endl; return (width * height / 2); } }; int main() { Shape *shape; Rectangle rec(10,7); Triangle tri(10,5); shape = &rec; shape->area(); shape = &tri; shape->area(); return 0; } |
Parent class area :
Parent class area :
Liked this program? Do Like & share with your friends.
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.