fork download
  1. // dynamic allocation and polymorphism
  2. #include <iostream>
  3. using namespace std;
  4.  
  5. class Polygon {
  6. protected:
  7. int width, height;
  8. public:
  9. Polygon (int a, int b) : width(a), height(b) {}
  10. virtual int area (void) =0;
  11. void printarea()
  12. { cout << this->area() << '\n'; }
  13. };
  14.  
  15. class Rectangle: public Polygon {
  16. public:
  17. Rectangle(int a,int b) : Polygon(a,b) {}
  18. int area()
  19. { return width*height; }
  20. };
  21.  
  22. class Triangle: public Polygon {
  23. public:
  24. Triangle(int a,int b) : Polygon(a,b) {}
  25. int area()
  26. { return width*height/2; }
  27. };
  28.  
  29. int main () {
  30. Polygon * ppoly1 = new Rectangle (4,5);
  31. Polygon * ppoly2 = new Triangle (4,5);
  32. ppoly1->printarea();
  33. ppoly2->printarea();
  34. delete ppoly1;
  35. delete ppoly2;
  36. return 0;
  37. }
Success #stdin #stdout 0s 4284KB
stdin
Standard input is empty
stdout
20
10