#include <iostream>
#include <memory>
using namespace std;
class Base {
private:
// data members
public:
Base() { cout << "Base created" << endl; }
Base(const Base &) { cout << "Base copied" << endl; }
virtual ~Base() { cout << "Base destroyed" << endl; }
// ...
virtual Base* clone() const = 0;
};
class Derived : public Base{
private:
// more data members
public:
Derived(){ cout << "Derived created" << endl; }
Derived(const Derived &){ cout << "Derived copied" << endl; }
~Derived(){ cout << "Derived destroyed" << endl; }
// ...
Derived* clone() const override {
return new Derived(*this);
}
};
class DecoratedDerived : public Base {
private:
unique_ptr<Base> ptr;
// ...
public:
DecoratedDerived()
: Base(), ptr(new Derived)
{
cout << "DecoratedDerived created" << endl;
}
DecoratedDerived(const DecoratedDerived &src)
: Base(src), ptr(src.ptr ? src.ptr->clone() : nullptr)
{
cout << "DecoratedDerived copied" << endl;
}
~DecoratedDerived() {
cout << "DecoratedDerived destroyed" << endl;
}
// ...
DecoratedDerived* clone() const override{
return new DecoratedDerived(*this);
}
};
int main()
{
cout << "creating DecoratedDerived..." << endl;
auto *p_d = new DecoratedDerived;
cout << endl;
cout << "cloning DecoratedDerived..." << endl;
auto *p_clone = p_d->clone();
cout << endl;
cout << "destroying clone..." << endl;
delete p_clone;
cout << endl;
cout << "destroying DecoratedDerived..." << endl;
delete p_d;
cout << endl;
return 0;
}