fork download
  1. #include <iostream>
  2. #include <memory>
  3. using namespace std;
  4.  
  5. class Base {
  6. private:
  7. // data members
  8. public:
  9. Base() { cout << "Base created" << endl; }
  10. Base(const Base &) { cout << "Base copied" << endl; }
  11. virtual ~Base() { cout << "Base destroyed" << endl; }
  12. // ...
  13. virtual Base* clone() const = 0;
  14. };
  15.  
  16. class Derived : public Base{
  17. private:
  18. // more data members
  19. public:
  20. Derived(){ cout << "Derived created" << endl; }
  21. Derived(const Derived &){ cout << "Derived copied" << endl; }
  22. ~Derived(){ cout << "Derived destroyed" << endl; }
  23. // ...
  24. Derived* clone() const override {
  25. return new Derived(*this);
  26. }
  27. };
  28.  
  29. class DecoratedDerived : public Base {
  30. private:
  31. unique_ptr<Base> ptr;
  32. // ...
  33. public:
  34. DecoratedDerived()
  35. : Base(), ptr(new Derived)
  36. {
  37. cout << "DecoratedDerived created" << endl;
  38. }
  39. DecoratedDerived(const DecoratedDerived &src)
  40. : Base(src), ptr(src.ptr ? src.ptr->clone() : nullptr)
  41. {
  42. cout << "DecoratedDerived copied" << endl;
  43. }
  44. ~DecoratedDerived() {
  45. cout << "DecoratedDerived destroyed" << endl;
  46. }
  47. // ...
  48. DecoratedDerived* clone() const override{
  49. return new DecoratedDerived(*this);
  50. }
  51. };
  52.  
  53. int main()
  54. {
  55. cout << "creating DecoratedDerived..." << endl;
  56. auto *p_d = new DecoratedDerived;
  57. cout << endl;
  58.  
  59. cout << "cloning DecoratedDerived..." << endl;
  60. auto *p_clone = p_d->clone();
  61. cout << endl;
  62.  
  63. cout << "destroying clone..." << endl;
  64. delete p_clone;
  65. cout << endl;
  66.  
  67. cout << "destroying DecoratedDerived..." << endl;
  68. delete p_d;
  69. cout << endl;
  70.  
  71. return 0;
  72. }
Success #stdin #stdout 0.01s 5476KB
stdin
Standard input is empty
stdout
creating DecoratedDerived...
Base created
Base created
Derived created
DecoratedDerived created

cloning DecoratedDerived...
Base copied
Base created
Derived copied
DecoratedDerived copied

destroying clone...
DecoratedDerived destroyed
Derived destroyed
Base destroyed
Base destroyed

destroying DecoratedDerived...
DecoratedDerived destroyed
Derived destroyed
Base destroyed
Base destroyed