fork download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <memory>
  4. #include <string>
  5. #include <vector>
  6.  
  7. class Polygon
  8. {
  9. public:
  10. virtual unsigned int Area() const = 0;
  11. };
  12.  
  13. class Rectangle : public Polygon
  14. {
  15. public:
  16. Rectangle() : m_width(1), m_height(1) { }
  17.  
  18. Rectangle(unsigned int h, unsigned int w) : m_width(w), m_height(h)
  19. { }
  20.  
  21. Rectangle(const Rectangle& r) : m_width(r.m_width), m_height(r.m_height)
  22. { }
  23.  
  24. virtual ~Rectangle()
  25. { }
  26.  
  27. Rectangle& operator= (Rectangle r)
  28. {
  29. std::swap(*this, r);
  30. return *this;
  31. }
  32.  
  33. virtual unsigned int Area() const
  34. {
  35. return m_width * m_height;
  36. }
  37.  
  38. private:
  39. unsigned int m_width;
  40. unsigned int m_height;
  41. };
  42.  
  43. class Triangle : public Polygon
  44. {
  45. public:
  46. Triangle() : m_base(1), m_height(1) { }
  47.  
  48. Triangle(unsigned int h, unsigned int b) : m_base(b), m_height(h)
  49. { }
  50.  
  51. Triangle(const Triangle& r) : m_base(r.m_base), m_height(r.m_height)
  52. { }
  53.  
  54. virtual ~Triangle()
  55. { }
  56.  
  57. Triangle& operator= (Triangle r)
  58. {
  59. std::swap(*this, r);
  60. return *this;
  61. }
  62.  
  63. virtual unsigned int Area() const
  64. {
  65. return m_base * m_height / 2;
  66. }
  67.  
  68. private:
  69. unsigned int m_base;
  70. unsigned int m_height;
  71. };
  72.  
  73. std::ostream& operator<<(std::ostream& os, const Rectangle& r)
  74. {
  75. os << "Area of rectangle is: " << r.Area();
  76. return os;
  77. }
  78.  
  79. std::ostream& operator<<(std::ostream& os, const Triangle& r)
  80. {
  81. os << "Area of Triangle is: " << r.Area();
  82. return os;
  83. }
  84.  
  85. int main()
  86. {
  87. Rectangle r(4, 5);
  88. Triangle t(4, 5);
  89. std::cout << r << "\n" << t << "\n";
  90.  
  91. std::vector<std::unique_ptr<Polygon>> v;
  92. v.emplace_back(new Rectangle(4, 5));
  93. v.emplace_back(new Triangle(4, 5));
  94. std::for_each(v.begin(), v.end(), [](const std::unique_ptr<Polygon>& p)
  95. {
  96. std::cout << "Area of this polygon is " << p->Area() << "\n";
  97. });
  98. return 0;
  99. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
Area of rectangle is:  20
Area of Triangle is:  10
Area of this polygon is 20
Area of this polygon is 10