avr39ripe

cppAgregationCompositionExample

Aug 10th, 2021
1,670
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3.  
  4. class List
  5. {
  6. public:
  7.     List() { std::cout << "List constructed\n"; }
  8.     ~List() { std::cout << "List Destructed\n"; }
  9. };
  10.  
  11. class Stack
  12. {
  13.     List* storage;
  14. public:
  15.     Stack() : storage{ new List } { std::cout << "Stack constructed\n"; }
  16.     ~Stack() { delete storage;  std::cout << "Stack Destructed\n"; }
  17. };
  18.  
  19.  
  20. class Hummer
  21. {
  22. public:
  23.     Hummer() { std::cout << "Hummer constructed\n"; }
  24.     ~Hummer() { std::cout << "Hummer Destructed\n"; }
  25.     void use() { std::cout << "Boom!\n"; }
  26. };
  27.  
  28. class Master
  29. {
  30.     Hummer& tool;
  31. public:
  32.     Master(Hummer& h) : tool{h} { std::cout << "Master constructed with tool\n"; }
  33.     //Master() : tool{ nullptr } { std::cout << "Master constructed without tool\n"; }
  34.     ~Master() { std::cout << "Master Destructed\n"; }
  35.     //void useTool() { if (tool) { tool->use(); } else { std::cout << "NO TOOLS\n"; } }
  36.     void useTool() { tool.use(); }
  37. };
  38.  
  39. int main()
  40. {
  41.     //Stack s;
  42.     Hummer h;
  43.     {
  44.         Master m{h};
  45.         m.useTool();
  46.     }
  47.    
  48.     std::cout << "Hummer is still alive! :)\n";
  49.     h.use();
  50.  
  51.     return 0;
  52. }
  53.  
RAW Paste Data