fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. class Shape {
  5. public:
  6. virtual double area() = 0;
  7. virtual ~Shape() {}
  8. };
  9.  
  10. class Circle : public Shape {
  11. double r;
  12. public:
  13. Circle(double radius) : r(radius) {}
  14. double area() { return 3.14 * r * r; }
  15. };
  16.  
  17. class Rectangle : public Shape {
  18. double w, h;
  19. public:
  20. Rectangle(double width, double height) : w(width), h(height) {}
  21. double area() { return w * h; }
  22. };
  23.  
  24. class Triangle : public Shape {
  25. double b, h;
  26. public:
  27. Triangle(double base, double height) : b(base), h(height) {}
  28. double area() { return 0.5 * b * h; }
  29. };
  30.  
  31. void printArea(Shape* shape) {
  32. cout << shape->area() << endl;
  33. }
  34.  
  35. int main() {
  36. Circle c(5);
  37. Rectangle r(4, 6);
  38. Triangle t(3, 4);
  39.  
  40. printArea(&c);
  41. printArea(&r);
  42. printArea(&t);
  43.  
  44. return 0;
  45. }
Success #stdin #stdout 0.01s 5324KB
stdin
Standard input is empty
stdout
78.5
24
6