Advertisement
vvccs

POLYMORPHISM

Jun 6th, 2023
33
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.96 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class Shape
  5. {
  6. protected:
  7.     int width, height;
  8.  
  9. public:
  10.     Shape(int a, int b)
  11.     {
  12.         width = a;
  13.         height = b;
  14.     }
  15.     virtual int area() = 0;
  16. };
  17. // Rectangle : -
  18. class Rectangle : public Shape{
  19.     public :
  20.         Rectangle(int a, int b) : Shape(a, b){}
  21.         int area()
  22.         {
  23.         cout << "Rectangle class area :" << (width * height) << endl;
  24.         }
  25. };
  26. // Triangle : -
  27.  
  28. class Triangle : public Shape
  29. {
  30. public:
  31.     Triangle(int a, int b) : Shape(a, b) {}
  32.     int area()
  33.     {
  34.         cout << "Triangle class area :" << (width * height / 2) << endl;
  35.     }
  36. };
  37. int main()
  38. {
  39.     Shape *shape;
  40.     Rectangle rec(20, 14);
  41.     Triangle tri(20, 10);
  42.     // store the address of rectangle
  43.     shape = &rec;
  44.     // call rectangle area.
  45.     shape->area();
  46.     // store the address of triangle
  47.     shape = &tri;
  48.     // call triangle area.
  49.     shape->area();
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement