/*
C.67: A base class should suppress copying, and provide a virtual clone instead if "copying" is desired
Reason
To prevent slicing, because the normal copy operations will copy only the base portion of a derived object.
*/
// Example, bad
class B { // BAD: base class doesn't suppress copying
int data;
// ... nothing about copy operations, so uses default ...
};
class D : public B {
string moredata; // add a data member
// ...
};
auto d = make_unique<D>();
auto b = make_unique<B>(d); // oops, slices the object; gets only d.data but drops d.moredata
// Example, Good
class B { // GOOD: base class suppresses copying
int data;
B(const B&) =delete;
B& operator=(const B&) =delete;
virtual unique_ptr<B> clone() { return /* B object */; }
// ...
};
class D : public B {
string moredata; // add a data member
unique_ptr<B> clone() override { return /* D object */; }
// ...
};
auto d = make_unique<D>();
auto b = d.clone(); // ok, deep clone
// TODO: COVARIANT return type does not exist for smart pointers. So try to complete the above snippet.