fork download
  1. #include <iostream>
  2. #include <string>
  3.  
  4. class shape
  5. {
  6. public:
  7. void setValues(int height_, int width_)
  8. {
  9. height = height_;
  10. width = width_;
  11. }
  12.  
  13. virtual int area() = 0; // This is needed for polymorphism to work
  14.  
  15. virtual std::string name() = 0;
  16.  
  17. protected:
  18. int height;
  19. int width;
  20. };
  21.  
  22. class rectangle : public shape
  23. {
  24. public:
  25. int area()
  26. {
  27. return height * width;
  28. }
  29.  
  30. std::string name()
  31. {
  32. return "Rectangle";
  33. }
  34. };
  35.  
  36. class triangle :public shape
  37. {
  38. public:
  39. int area()
  40. {
  41. return height * width / 2;
  42. }
  43.  
  44. std::string name()
  45. {
  46. return "Triangle";
  47. }
  48. };
  49.  
  50. void print_area(shape& poly)
  51. {
  52. std::cout << poly.name() << ' ' << poly.area() << '\n';
  53. }
  54.  
  55. int main()
  56. {
  57. rectangle rect;
  58. triangle trng;
  59.  
  60. rect.setValues(2, 3);
  61. trng.setValues(5, 4);
  62.  
  63. print_area(rect);
  64. print_area(trng);
  65. }
  66.  
Success #stdin #stdout 0s 3412KB
stdin
Standard input is empty
stdout
Rectangle 6
Triangle 10