fork download
  1. #include <iostream>
  2. #include <memory>
  3. using namespace std;
  4.  
  5. //Extras
  6. class ShapeExtra
  7. {
  8. public:
  9. ShapeExtra() {}
  10. void ShapeFunc() { std::cout << "Shape"; }
  11. virtual ~ShapeExtra() = default; //Important!
  12. };
  13.  
  14. class Shape
  15. {
  16. public:
  17. std::unique_ptr<ShapeExtra> m_var;
  18.  
  19. //require a pointer on construction
  20. //make sure to document, that Shape class takes ownership and handles deletion
  21. Shape(ShapeExtra* p):m_var(p){}
  22.  
  23. //The common functions
  24. ShapeExtra& GetVar(){ return *m_var; }
  25. void ShapeFunc() {m_var->ShapeFunc();}
  26. };
  27.  
  28.  
  29. class CircleExtra : public ShapeExtra
  30. {
  31. public:
  32. void CircleExtraFunc() {std::cout << "Circle";}
  33. };
  34.  
  35. class Circle : public Shape
  36. {
  37. CircleExtra* m_var;
  38.  
  39. public:
  40. Circle() : Shape(new CircleExtra()) {
  41. m_var = static_cast<CircleExtra*>(Shape::m_var.get());
  42. }
  43.  
  44. void CircleFunc()
  45. {
  46. m_var->CircleExtraFunc();
  47. }
  48. };
  49.  
  50.  
  51. int main() {
  52. Circle c;
  53. //use the ShapeExtra Object
  54. c.GetVar().ShapeFunc();
  55. //call via forwarded function
  56. c.ShapeFunc();
  57. //call the circleExtra Function
  58. c.CircleFunc();
  59. return 0;
  60. }
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
ShapeShapeCircle