Skip to content

Prototype

Difficulty: Intermediate

Key concepts

  • prototype pattern
  • virtual clone
  • deep copy
  • shallow copy
  • object slicing
  • value types and std::variant
  • The problem Prototype solves, shown before the pattern is named: code that must copy an object it knows only through a base class, and so does not know which constructor to call.
  • How a virtual clone() that returns std::unique_ptr<Base> lets each class copy itself, so the copying code never names a concrete class.
  • The difference between a deep and a shallow copy, and why an object that owns other objects must copy them too.
  • When plain value types (a std::variant, or just a copy constructor) make the pattern unnecessary.

A team writes a small diagram editor. A palette at the side of the window holds ready-made shapes, called presets. Clicking a preset places a new shape on the canvas.

Requirements:

  1. FR-1 The palette holds named presets: a red dot, a note that says “TODO”, and so on. Placing a preset puts a new shape on the canvas, set up exactly like the preset.
  2. FR-2 The user can select shapes, group them, and save the group as a new preset while the editor runs. Placing it places a copy of the whole group.
  3. FR-3 Every placed shape is independent. Moving one shape, or one shape inside a placed group, changes nothing else: not other placed shapes, and not the preset.
  4. FR-4 Other teams add new kinds of shape (arrows, images) as classes derived from Shape. The palette and the code that copies shapes must not change when they do.

Where Prototype shows up in requirements. Listen for “save as preset” or “save as template”, “duplicate”, “copy and paste”, and “make another one like this”, where “this” is an object the user set up, not a class in the code. The signal in code is an object known only through a base class pointer that has to be copied. Prototype comes up rarely in modern C++: when the set of types is known, plain value types copy themselves, as the end of this page shows.

The palette and the canvas hold shapes as std::unique_ptr<Shape>, because a canvas holds several kinds. To place a preset, the editor must copy a Shape it knows only through a reference. C++ has no virtual constructors, so a copy constructor cannot be chosen at run time. The obvious workaround is to ask the object what it is:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

before.cpp
// Copy a shape known only through a base reference: ask what it is.
// Returns a new copy owned by the caller, for the kinds this function
// lists (Circle and Label); throws std::logic_error for any other kind.
std::unique_ptr<Shape> copy_shape(const Shape& shape) {
// dynamic_cast<const Circle*>(&shape) asks, while the program runs,
// "is this Shape really a Circle?". If it is, the result points to it
// as a Circle; if not, it is nullptr. The `if` declares `circle` and
// tests it in one go: the branch runs only for a non-null pointer.
// Inside, *circle is a Circle, so Circle's copy constructor can be
// called.
if (const auto* circle = dynamic_cast<const Circle*>(&shape)) {
return std::make_unique<Circle>(*circle);
}
// The same question for Label. Each kind needs its own branch here.
if (const auto* label = dynamic_cast<const Label*>(&shape)) {
return std::make_unique<Label>(*label);
}
// Where it goes wrong: every kind not listed above ends up here.
// Group was added later, by someone who did not know about this function.
// The compiler cannot catch the gap; it shows up only when a program
// tries to copy a group.
throw std::logic_error{"copy_shape: unknown kind of shape"};
}

Two tests pin down what it does:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_shapes.cpp
// LLD_TEST(name) defines one test. LLD_CHECK_EQ(actual, expected) fails
// the test, printing both values, unless they are equal, and
// LLD_CHECK_THROWS(expression, type) fails unless the expression throws
// that type of exception. They come from the site's small test header,
// lld_test.hpp.
// The first test holds a Circle through a Shape& (as the palette would)
// and proves copy_shape makes a Circle with the same values.
LLD_TEST(before_copies_the_kinds_it_was_written_for) {
const Circle dot{1, 2, 4, "red"};
const Shape& shape = dot;
const auto copy = before::copy_shape(shape);
LLD_CHECK_EQ(copy->describe(), std::string{"red circle r4 at (1,2)"});
}
// A new kind compiles everywhere and fails only when someone copies it.
// copy_shape has no Group branch, so copying an (empty) group throws.
LLD_TEST(before_fails_at_run_time_for_a_newer_kind) {
const Group group{"callout"};
const Shape& shape = group;
LLD_CHECK_THROWS(before::copy_shape(shape), std::logic_error);
}
  • FR-4 fails. The function names every concrete class. A new kind of shape compiles everywhere, then fails when someone copies it. Nothing tells the author of Arrow that this function exists.
  • FR-2 fails for the same reason: Group was added after copy_shape, so a saved group cannot be placed. Even with a Group branch added, that branch would have to copy the children, which means calling copy_shape on each: the chain grows with every kind.

Two other first ideas do not work either:

  • Copy through the base: auto copy = *preset;. Shape is abstract, so this does not compile. If it were concrete, it would compile and keep only the Shape part of the object, a bug called object slicing.
  • A maker function per preset, as in Factory Method: std::make_unique<Circle>(0, 0, 4, "red") stored in a std::function. That works for presets written in the code, but not for FR-2. A group the user saved is data, made while the program runs; there is no function in the code that makes it.

Look at what each part of the problem needs, and which class alone has the knowledge for it:

Data or job Who knows it Where it goes
position, radius, colour, text each concrete shape its data members, copied by its copy constructor
a group’s children the group, which owns them a data member std::vector<std::unique_ptr<Shape>>; copied deeply by a hand-written copy constructor
“make another object of my exact type, set up like me” only the object itself a virtual function clone() const, overridden in every concrete class
move, describe each concrete shape virtual functions, as before
the presets, by name the palette Palette: one prototype per name; make() asks the prototype to clone itself
copying a Shape without knowing its type nobody: it would slice forbidden: Shape’s copy constructor is protected and its assignment is deleted

The key row is the third. “Which concrete class is this?” is a question only the object can answer, so the copy is a member function of the object. That one decision removes every dynamic_cast from the code that copies.

The functions sort into two groups: clone(), move_by(), and describe() are virtual, because their behaviour depends on the concrete class; Palette::make() and Palette::add() are ordinary member functions of a final class, because the palette works the same way for every kind of shape.

Prototype creates new objects by copying a configured object, the prototype, rather than by naming a class. Each class provides a clone() member function that returns a copy of itself, so code holding only a base class pointer can still make an exact, independent copy.

The roles:

  • Prototype interface: Shape, which declares clone().
  • Concrete prototypes: Circle, Label, and Group, each of which implements clone() by copying itself.
  • Client: Palette, which keeps one prototype per name and clones it on request, and any code that duplicates shapes on the canvas.

interface (abstract class) Shape

the prototype interface

Member functions

  • virtual std::unique_ptr<Shape> clone() const = 0; a new, independent copy
  • virtual void move_by(int dx, int dy) = 0;
  • virtual std::string describe() const = 0;
  • Shape(const Shape&); protected: only derived copy constructors use it
  • Shape& operator=(const Shape&) = delete; no slicing assignment

class Circle final

a concrete prototype; Label is the same shape of class

Data members

  • int x_;
  • int y_;
  • int radius_;
  • std::string colour_;

Member functions

  • std::unique_ptr<Shape> clone() const override; make_unique<Circle>(*this)

class Group final

a concrete prototype that owns other shapes

Data members

  • std::string name_;
  • std::vector<std::unique_ptr<Shape>> children_; owned

Member functions

  • Group(const Group& other); deep copy: clones each child
  • void add(std::unique_ptr<Shape> child); throws for null
  • std::unique_ptr<Shape> clone() const override; make_unique<Group>(*this)

class Palette final

the client

Data members

  • std::map<std::string, std::unique_ptr<Shape>, std::less<>> presets_; one prototype per name

Member functions

  • void add(std::string name, std::unique_ptr<Shape> preset); throws for empty, null, or taken names
  • std::unique_ptr<Shape> make(std::string_view name) const; preset(name).clone()
  • const Shape& preset(std::string_view name) const;
Each shape copies itself; the palette never names a concrete class

The outline leaves out Label, which has the same form as Circle, the move_by and describe overrides in each concrete class, Group::size(), and Palette::names().

Palette and Group own shapes through the Shape interface; every concrete shape implements clone()
Text description of the diagram

Shape is an interface with three pure virtual functions: clone, which returns a unique_ptr to Shape, move_by, and describe. Circle (with x, y, radius, and colour), Label (with x, y, and text), and Group (with a name and a vector of children) each implement Shape and override clone. Group also has a hand-written copy constructor and an add function. Group owns zero or more Shapes as its children, and Palette owns zero or more Shapes as its presets; both relationships are composition, shown with a filled diamond. Palette has add and make, and make returns a unique_ptr to Shape.

Diagram source (Mermaid)
classDiagram
class Shape {
  <<interface>>
  +clone() unique_ptr~Shape~*
  +move_by(dx, dy)*
  +describe() string*
}
class Circle {
  -x_ y_ radius_ colour_
  +clone() unique_ptr~Shape~
}
class Label {
  -x_ y_ text_
  +clone() unique_ptr~Shape~
}
class Group {
  -name_ string
  -children_ vector
  +Group(const Group&)
  +add(child)
  +clone() unique_ptr~Shape~
}
class Palette {
  -presets_ map
  +add(name, preset)
  +make(name) unique_ptr~Shape~
}
Shape <|.. Circle
Shape <|.. Label
Shape <|.. Group
Group "1" *-- "0..*" Shape : children
Palette "1" *-- "0..*" Shape : presets

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

shape.hpp
// Anything that can be placed on the canvas: the prototype interface.
// Code that holds a Shape only through a Shape& or a
// std::unique_ptr<Shape> does not know whether it is a Circle, a Label,
// or a Group, so it cannot call the right copy constructor itself.
// Instead it asks the object to copy itself, with clone(). clone,
// move_by, and describe are "= 0" (pure virtual): Shape is abstract, so
// nobody can create a plain Shape, only a derived class that fills them
// in.
class Shape {
public:
// Virtual, because shapes are deleted through std::unique_ptr<Shape>:
// without it, deleting a Circle through a Shape pointer would be
// undefined behaviour (in practice, the Circle's own members, such as
// its colour string, would not be cleaned up).
virtual ~Shape() = default;
// "= delete" removes copy assignment. Through two Shape& references,
// `*a = *b` could copy only the Shape part and leave the rest of `*a`
// as it was (slicing), so it is not allowed at all.
Shape& operator=(const Shape&) = delete; // no slicing assignment through a base
// Returns a new, independent copy of the whole object, of the same
// concrete type, owned by the caller. A Circle returns a new Circle,
// a Group a new Group with copies of its children. The return type is
// std::unique_ptr<Shape> in every class: the caller owns the copy and
// it is deleted automatically. `const`: copying does not change the
// original.
virtual std::unique_ptr<Shape> clone() const = 0;
// Move the shape by dx to the right and dy down.
virtual void move_by(int dx, int dy) = 0;
// One line of text for the demo and the tests, such as
// "red circle r4 at (0,0)".
virtual std::string describe() const = 0;
protected:
// Protected: only derived classes can use these. A derived class's
// constructor calls Shape(), and its copy constructor calls
// Shape(const Shape&), but no other code can construct or copy a
// bare Shape. "= default" asks the compiler for the usual version.
Shape() = default;
Shape(const Shape&) = default; // for the derived classes' copy constructors
};
  • clone() returns std::unique_ptr<Shape>. The copy is a new object on the heap, and the caller owns it. A raw Shape* would leave the caller guessing whether to delete it.
  • The return type cannot be std::unique_ptr<Circle> in Circle. C++ allows a narrower return type in an override (a covariant return) only for raw pointers and references, and std::unique_ptr<Circle> is not a pointer to a class derived from std::unique_ptr<Shape>. Compilers reject it as an invalid covariant return type. This is rarely a loss: code that needs a Circle copy of a Circle it knows about can call the copy constructor.
  • The copy constructor is protected. Derived copy constructors can call it, but no other code can copy a Shape through the base. The copy assignment is deleted for the same reason: *a = *b through Shape& would copy only the Shape part.
  • The destructor is virtual, because shapes are destroyed through std::unique_ptr<Shape>.

Simple shapes clone through their copy constructors

Section titled “Simple shapes clone through their copy constructors”

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

shapes.hpp
// A filled circle with its centre at (x, y). One of the "leaf" shapes:
// it holds plain values (numbers and a string) and no other shapes.
// `final` means no class can derive from Circle, so no subclass can
// inherit Circle's clone() and be copied as a plain Circle by mistake.
// `override` on each function asks the compiler to check that it really
// replaces a virtual function of Shape.
class Circle final : public Shape {
public:
// The colour string is taken by value and moved into the member.
Circle(int x, int y, int radius, std::string colour);
// A new Circle with the same position, radius, and colour.
std::unique_ptr<Shape> clone() const override;
void move_by(int dx, int dy) override;
std::string describe() const override;
private:
int x_;
int y_;
int radius_;
std::string colour_;
};
// A piece of text at (x, y): the other leaf shape, built the same way.
class Label final : public Shape {
public:
Label(int x, int y, std::string text);
std::unique_ptr<Shape> clone() const override;
void move_by(int dx, int dy) override;
std::string describe() const override;
private:
int x_;
int y_;
std::string text_;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

shapes.cpp
// The member initialiser list (after the colon) sets each member before
// the body runs. std::move(colour) hands the string's contents to colour_
// instead of copying them: `colour` is this constructor's own copy and is
// not used again.
Circle::Circle(int x, int y, int radius, std::string colour)
: x_{x}, y_{y}, radius_{radius}, colour_{std::move(colour)} {}
// The whole of Prototype for a leaf. *this is the Circle being cloned;
// std::make_unique<Circle>(*this) creates a new Circle on the heap by
// calling Circle's copy constructor with it, and returns a
// std::unique_ptr<Circle>. That converts to the declared return type,
// std::unique_ptr<Shape>, because a Circle is a Shape. The copy
// constructor is the one the compiler wrote: copying two ints, the
// radius, and a std::string is already a full, independent copy. The
// word Circle in this line is what makes the copy a Circle, which is why
// every concrete class must write its own clone().
std::unique_ptr<Shape> Circle::clone() const {
return std::make_unique<Circle>(*this); // the copy constructor does the work
}
void Circle::move_by(int dx, int dy) {
x_ += dx;
y_ += dy;
}
// For example "red circle r4 at (0,0)". at(x, y), a small helper above,
// makes the " at (x,y)" part; std::to_string turns a number into text.
std::string Circle::describe() const {
return colour_ + " circle r" + std::to_string(radius_) + at(x_, y_);
}

clone() is one line, std::make_unique<Circle>(*this): it calls the copy constructor, which the compiler wrote, because every member of Circle copies itself correctly. Each concrete class must write this line for itself. The class name in it is what makes the copy the right type, so it cannot be inherited.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

shapes.hpp
// Shapes that move together. A group owns its children, so copying a
// group must copy every child: a deep copy.
// Group is itself a Shape, so a group can hold other groups, and the
// palette can store a group as a preset like any other shape.
class Group final : public Shape {
public:
// A new group with a name and no children. `explicit` stops a plain
// string from turning into a Group by accident.
explicit Group(std::string name);
// The copy constructor is written by hand. The compiler's version
// would copy children_ element by element, and a std::unique_ptr
// cannot be copied, so copying a group would not compile. This one
// copies the name and clones each child instead.
Group(const Group& other); // clones each child
// Takes ownership of `child`: the caller hands it over with std::move
// or passes a fresh std::make_unique result, and the group deletes it
// when the group is destroyed.
void add(std::unique_ptr<Shape> child); // throws std::invalid_argument for null
std::size_t size() const { return children_.size(); }
std::unique_ptr<Shape> clone() const override;
void move_by(int dx, int dy) override;
std::string describe() const override;
private:
std::string name_;
// The children, in the order they were added. Each unique_ptr owns
// one child; the vector owns the unique_ptrs. So destroying a group
// destroys all its children, and their children, automatically.
std::vector<std::unique_ptr<Shape>> children_;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

shapes.cpp
Group::Group(std::string name) : name_{std::move(name)} {}
// The deep copy. `other` is the group being copied; the new group starts
// with no children and gets its own copy of each of other's children.
// - Shape{other} runs the base class's protected copy constructor for
// the Shape part of this object.
// - name_{other.name_} copies the name (a std::string copies itself).
// - reserve(n) makes room for n children up front, so push_back below
// does not have to grow the vector several times.
// - Each child is known only as a Shape, so it cannot be copied with a
// constructor call; child->clone() asks it to copy itself. If the
// child is itself a Group, its clone() runs this same constructor
// for its own children, so groups inside groups are copied all the
// way down.
// `const auto& child` is a reference to each std::unique_ptr in the
// other group: it reads the pointer without copying it (a unique_ptr
// cannot be copied anyway). push_back takes the new unique_ptr returned
// by clone(), so this group owns the copy; other's children are not
// changed.
// If a clone() throws partway, the half-built group's children_ is still
// destroyed, and with it the children copied so far, so nothing leaks.
Group::Group(const Group& other) : Shape{other}, name_{other.name_} {
children_.reserve(other.children_.size());
for (const auto& child : other.children_) {
children_.push_back(child->clone());
}
}
// Refuses a null pointer, so every child can safely be used with ->
// later. std::move(child) hands ownership on to the vector: after it,
// the parameter `child` is empty and the group owns the shape.
void Group::add(std::unique_ptr<Shape> child) {
if (!child) {
throw std::invalid_argument{"a group cannot hold a null shape"};
}
children_.push_back(std::move(child));
}
// The same one line as Circle's. It calls the hand-written copy
// constructor above, which is where the deep copy happens.
std::unique_ptr<Shape> Group::clone() const {
return std::make_unique<Group>(*this);
}
// Moving a group moves every child. `const auto&` only means the
// unique_ptr is not changed; the shape it points to can still be moved.
void Group::move_by(int dx, int dy) {
for (const auto& child : children_) {
child->move_by(dx, dy);
}
}
// For example: group callout [red circle r4 at (0,0); label "Look here"
// at (8,0)]. The `?:` puts "; " before every child except the first,
// so the children are separated without a stray "; " at either end.
// Each child's own describe() runs, so nested groups print nested.
std::string Group::describe() const {
std::string out = "group " + name_ + " [";
for (std::size_t i = 0; i < children_.size(); ++i) {
out += (i == 0 ? "" : "; ") + children_[i]->describe();
}
return out + "]";
}
How this code works: Group's copy constructor: the deep copy

Follow palette.make("callout") from the demo below. The callout preset is a group with two children: a red circle at (0,0) and the label “Look here” at (8,0).

  1. make calls clone() on the preset. The preset is a Group, so Group::clone() runs: std::make_unique<Group>(*this) creates a new group by calling Group(const Group& other), with other being the preset.

  2. The parts that copy themselves. Shape{other} copies the base part (it has no data, but it must be constructed), and name_{other.name_} copies the string "callout". At this point the new group’s children_ is an empty vector.

  3. reserve(2). The preset has two children, so room for two is made at once.

  4. The loop clones each child. The table shows what each step adds to the new group:

    step child in the preset child->clone() runs new group’s children_ after push_back
    1 red circle r4 at (0,0) Circle::clone() a new circle at (0,0)
    2 label “Look here” at (8,0) Label::clone() the new circle, and a new label at (8,0)
  5. clone() hands the new group back as a std::unique_ptr<Shape>, and make returns it to the caller.

The new group’s children are separate objects, so the demo’s move_by(0, 50) moves them to (0,50) and (8,50) while the preset’s stay at (0,0) and (8,0), as the output shows.

Groups inside groups. If a child is itself a Group, step 4 calls Group::clone() on it, which runs this same constructor for that child’s children. Each level copies the level below it, so the whole tree is copied, however deep. The test cloning_a_group_copies_every_child_at_every_depth checks a group two levels deep.

Why a hand-written constructor at all. A std::unique_ptr cannot be copied, so the copy constructor the compiler would write (which copies children_ element by element) does not compile when a group is copied. Writing it by hand is where the decision “copying a group copies its children” is made.

A group owns its children. Copying the group must therefore copy each child as well, and each child’s children, all the way down: a deep copy. Each child is again known only as a Shape, so the copy constructor calls child->clone() on each, and the recursion takes care of groups inside groups.

The compiler helps here. A class with a std::vector<std::unique_ptr<Shape>> member gets no usable copy constructor, because std::unique_ptr cannot be copied. Without the hand-written one, std::make_unique<Group>(*this) does not compile. The compiler forces the decision “what does copying a group mean?”. The exercise shows what happens when it does not. One surprise: type traits such as std::is_copy_constructible_v<Group> still report such a class as copyable, because they look only at the declaration of std::vector’s copy constructor; the error appears only when a copy is actually compiled.

The copy constructor passes other to Shape{other}, the protected base copy constructor, and reserves space so the vector allocates once.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

palette.hpp
// Named presets. Each preset is a configured object, a prototype; making
// a shape from a preset clones it. The user can add presets while the
// program runs, so the palette cannot know their classes in advance.
class Palette final {
public:
// Stores `preset` under `name`; the palette owns it from now on (the
// caller passes it with std::move or straight from std::make_unique).
// Throws std::invalid_argument for an empty name, a null preset, or
// a name already in use.
void add(std::string name, std::unique_ptr<Shape> preset);
// A new copy of the preset, owned by the caller. Throws
// std::invalid_argument for an unknown name. The preset itself is not
// changed, which is why make can be const. std::string_view is a
// read-only view of some text, so a caller can pass "dot" without a
// std::string being built for the call.
std::unique_ptr<Shape> make(std::string_view name) const;
// The stored preset itself, to look at (for example to describe it).
// It is a reference into the palette, not a copy: it is valid only
// while the palette and that preset exist.
const Shape& preset(std::string_view name) const; // throws like make
std::vector<std::string> names() const; // sorted
private:
// Name to preset. The map owns each preset through its unique_ptr,
// and keeps the names sorted. The third argument, std::less<>, is a
// "transparent" comparison: it lets find() compare a std::string_view
// with the stored std::string keys directly, without first making a
// std::string from the view.
std::map<std::string, std::unique_ptr<Shape>, std::less<>> presets_;
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

palette.cpp
// Find the preset (preset throws for an unknown name), then ask it to
// copy itself. clone() is virtual, so the preset's own class decides
// what kind of object the copy is: a Circle preset makes a Circle, a
// Group preset a Group with its own children. This file never names
// Circle, Label, or Group.
std::unique_ptr<Shape> Palette::make(std::string_view name) const {
return preset(name).clone();
}
// find returns an iterator: either one pointing at the map entry, whose
// key is found->first and whose value is found->second, or end(), which
// means "not found". found->second is the std::unique_ptr<Shape>, and
// the * in front gives the Shape it points to, returned by reference.
// std::string{name} turns the view into a std::string so it can be
// joined with + into the error message.
const Shape& Palette::preset(std::string_view name) const {
const auto found = presets_.find(name);
if (found == presets_.end()) {
throw std::invalid_argument{"no preset named '" + std::string{name} + "'"};
}
return *found->second;
}

The palette stores one prototype per name and answers make(name) with preset(name).clone(). It includes shape.hpp only. A preset the user saves while the editor runs is added like any other (FR-2), and a kind of shape written years later works unchanged (FR-4): a test below defines a new Arrow class inside the test and puts it in a palette.

std::less<> lets the map look names up by std::string_view without building a std::string first.

Object Owner Lives
a preset (a prototype) the Palette, by std::unique_ptr as long as the palette
a placed shape the canvas, from make() or clone() until the canvas drops it; independent of the preset
a group’s children the group, by std::unique_ptr as long as the group; a copied group owns its own copies
the Shape& from preset() the palette valid only while the palette and that preset exist

Nothing is shared. Every clone owns all of its parts, so FR-3 holds by construction: no two shapes point to the same data. preset() returns a reference for looking only; a caller that keeps it must not outlive the palette.

make() clones the preset, and the group's copy constructor clones each child
Text description of the diagram

The editor calls make(“callout”) on the Palette. The Palette calls clone() on the callout preset, which is a Group. The preset’s clone calls make_unique, which creates a new Group by running the copy constructor with the preset as the source. The new group copies the name; then, for each of the preset’s children, it calls clone() on that child and keeps the new child, which the new group owns. When the new group is complete, the preset’s clone returns a unique_ptr to it to the Palette, and the Palette returns it to the editor. The editor puts the new group on the canvas and moves it down by 50. The preset and its children are untouched.

Diagram source (Mermaid)
sequenceDiagram
participant E as editor
participant P as Palette
participant G as callout preset (Group)
participant N as new Group
participant C as preset's children
E->>P: make("callout")
P->>G: clone()
G->>N: make_unique, which runs Group(const Group&) with the preset
N->>N: copy the name
loop each of the preset's children
  N->>C: clone()
  C-->>N: a new child, owned by the new group
end
N-->>G: the new group, complete
G-->>P: unique_ptr to the new group
P-->>E: unique_ptr to the new group
E->>E: put it on the canvas, then move_by(0, 50)

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// Two presets. std::make_unique creates each shape on the heap and
// returns the std::unique_ptr that owns it; add takes that ownership,
// so from here on the palette owns the presets.
Palette palette;
palette.add("dot", std::make_unique<Circle>(0, 0, 4, "red"));
palette.add("note", std::make_unique<Label>(0, 0, "TODO"));
// The canvas owns the shapes placed on it. Each make() returns a new
// clone of the preset, and push_back moves that unique_ptr into the
// vector (it is a temporary, so no std::move is needed).
std::vector<std::unique_ptr<Shape>> canvas;
canvas.push_back(palette.make("dot"));
canvas.push_back(palette.make("dot"));
// back() is the last shape added: the second dot.
canvas.back()->move_by(30, 0); // moves this copy only
// The user builds a callout from two shapes and saves it as a preset.
auto callout = std::make_unique<Group>("callout");
callout->add(palette.make("dot"));
callout->add(std::make_unique<Label>(8, 0, "Look here"));
// std::move hands the group to the palette. `callout` is a named
// variable, so without std::move the call would try to copy it, and
// a unique_ptr cannot be copied: it would not compile. After this
// line `callout` is empty (null), so it must not be dereferenced.
palette.add("callout", std::move(callout));
// A deep copy of the saved group, moved down by 50. The preset and
// its two children stay where they were.
canvas.push_back(palette.make("callout"));
canvas.back()->move_by(0, 50);
// Print each placed shape, then each preset by name. names() is
// sorted, so the presets print as callout, dot, note.
for (const auto& shape : canvas) {
std::cout << "canvas: " << shape->describe() << '\n';
}
for (const auto& name : palette.names()) {
std::cout << "preset " << name << ": " << palette.preset(name).describe() << '\n';
}
How this code works: The demo: who owns each shape

Each line either creates a shape, hands one over, or copies one. Track where each shape lives:

  1. Two presets. std::make_unique creates a circle and a label, and add takes ownership: the palette now owns "dot" and "note".
  2. Two dots on the canvas. Each palette.make("dot") returns a new clone of the preset circle, owned by the returned std::unique_ptr, and push_back puts that pointer in canvas. The canvas now owns two circles, both at (0,0). canvas.back() is the second one, and move_by(30, 0) moves only it, to (30,0).
  3. A user-built group. callout owns a new, empty group. The first add gives it a third clone of the dot; the second gives it a new label at (8,0). Then std::move(callout) hands the whole group to the palette as the preset "callout"; callout is empty from then on.
  4. Placing the group. palette.make("callout") deep-copies the preset (see the walkthrough above), and move_by(0, 50) moves the copy and its two children down by 50.
  5. Printing. The first loop prints the three canvas shapes in the order they were added. The second prints each preset; names() is sorted, so they come out as callout, dot, note. The presets all still read (0,0) and (8,0): nothing done to a placed copy reached them.

When main ends, canvas and palette are destroyed, and every shape, including the children inside the groups, is deleted by the std::unique_ptr that owns it. There is no delete anywhere.

Expected output
canvas: red circle r4 at (0,0)
canvas: red circle r4 at (30,0)
canvas: group callout [red circle r4 at (0,50); label "Look here" at (8,50)]
preset callout: group callout [red circle r4 at (0,0); label "Look here" at (8,0)]
preset dot: red circle r4 at (0,0)
preset note: label "TODO" at (0,0)

Read the output against the requirements:

  • The two dots come from one preset, and moving the second left the first at (0,0) (FR-1, FR-3).
  • The callout was built from a palette dot and a new label, saved as a preset, and placed. The placed copy moved down by 50; the preset’s children are still at y = 0 (FR-2, FR-3).
  • The palette code has no Circle, Label, or Group in it, and the Arrow test below shows a new kind working unchanged (FR-4).

The tests check the type of a clone, that clones are independent at every depth, the palette’s rules, and the value-type alternative:

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_shapes.cpp
// static_assert checks a condition while the program is compiled: if it
// is false, the build fails. std::is_abstract_v<Shape> is true because
// Shape has pure virtual functions, so nobody can create a plain Shape.
// The second line proves the deleted operator= really is gone.
static_assert(std::is_abstract_v<Shape>);
static_assert(!std::is_copy_assignable_v<Shape>); // no slicing through a base reference
// LLD_CHECK(condition) fails the test if the condition is false.
// Clone a Label held as a Shape. dynamic_cast to Label* gives nullptr
// unless the copy really is a Label, so the first check proves clone()
// kept the concrete type. .get() gives the raw address a unique_ptr
// holds; different addresses prove the copy is a new object.
LLD_TEST(clone_keeps_the_concrete_type) {
const std::unique_ptr<Shape> original = std::make_unique<Label>(0, 0, "TODO");
const auto copy = original->clone();
LLD_CHECK(dynamic_cast<const Label*>(copy.get()) != nullptr);
LLD_CHECK(copy.get() != original.get());
}
// Move the copy and check both: only the copy moved.
LLD_TEST(a_clone_is_independent_of_its_original) {
const std::unique_ptr<Shape> original = std::make_unique<Circle>(0, 0, 4, "red");
const auto copy = original->clone();
copy->move_by(5, 5);
LLD_CHECK_EQ(copy->describe(), std::string{"red circle r4 at (5,5)"});
LLD_CHECK_EQ(original->describe(), std::string{"red circle r4 at (0,0)"});
}
// A group inside a group: outer holds inner (which holds a circle) and a
// label. Clone outer and move the clone right by 10. Every shape in the
// clone moved, even the circle two levels down, and every shape in the
// original stayed: the copy is deep at every level.
LLD_TEST(cloning_a_group_copies_every_child_at_every_depth) {
auto inner = std::make_unique<Group>("inner");
inner->add(std::make_unique<Circle>(0, 0, 1, "blue"));
Group outer{"outer"};
outer.add(std::move(inner));
outer.add(std::make_unique<Label>(2, 0, "hi"));
const auto copy = outer.clone();
copy->move_by(10, 0);
LLD_CHECK_EQ(copy->describe(),
std::string{"group outer [group inner [blue circle r1 at (10,0)]; "
"label \"hi\" at (12,0)]"});
LLD_CHECK_EQ(outer.describe(),
std::string{"group outer [group inner [blue circle r1 at (0,0)]; "
"label \"hi\" at (2,0)]"});
}
// add(nullptr) throws, and the group is left with no children.
LLD_TEST(a_group_refuses_a_null_child) {
Group group{"g"};
LLD_CHECK_THROWS(group.add(nullptr), std::invalid_argument);
LLD_CHECK_EQ(group.size(), std::size_t{0});
}
// Two copies from one preset: moving the first changes neither the
// second nor the preset.
LLD_TEST(palette_makes_independent_copies_of_a_preset) {
Palette palette;
palette.add("dot", std::make_unique<Circle>(0, 0, 4, "red"));
const auto first = palette.make("dot");
first->move_by(3, 0);
const auto second = palette.make("dot");
LLD_CHECK_EQ(second->describe(), std::string{"red circle r4 at (0,0)"});
LLD_CHECK_EQ(palette.preset("dot").describe(), std::string{"red circle r4 at (0,0)"});
}
// The palette never names a concrete class, so a kind defined after it
// was written, here inside the test, works without changing it.
LLD_TEST(palette_works_with_a_kind_it_has_never_seen) {
// A local class: defined inside this function, unknown to the rest
// of the program and to the palette. Its clone() is the usual one
// line. Its move_by leaves the second parameter unnamed because it
// does not use it; that keeps the compiler from warning.
class Arrow final : public Shape {
public:
std::unique_ptr<Shape> clone() const override { return std::make_unique<Arrow>(*this); }
void move_by(int dx, int) override { length_ += dx; }
std::string describe() const override { return "arrow " + std::to_string(length_); }
private:
int length_ = 10;
};
Palette palette;
palette.add("arrow", std::make_unique<Arrow>());
LLD_CHECK_EQ(palette.make("arrow")->describe(), std::string{"arrow 10"});
}
// Each refused call throws, and none of them adds anything: after an
// empty name, a null preset, a duplicate name, and an unknown name, the
// palette still holds just "dot".
LLD_TEST(palette_rejects_bad_presets_and_unknown_names) {
Palette palette;
palette.add("dot", std::make_unique<Circle>(0, 0, 4, "red"));
LLD_CHECK_THROWS(palette.add("", std::make_unique<Circle>(0, 0, 1, "red")),
std::invalid_argument);
LLD_CHECK_THROWS(palette.add("empty", nullptr), std::invalid_argument);
LLD_CHECK_THROWS(palette.add("dot", std::make_unique<Circle>(0, 0, 1, "red")),
std::invalid_argument);
LLD_CHECK_THROWS(palette.make("star"), std::invalid_argument);
LLD_CHECK_EQ(palette.names().size(), std::size_t{1});
}
// The value-type palette. std::get<values::Dot>(item) reads the Dot
// inside the variant (it would throw std::bad_variant_access if the
// item held a Note). Changing the copy's x leaves the preset at 0.
LLD_TEST(value_presets_copy_by_plain_assignment) {
values::Palette palette;
palette.add("dot", values::Dot{0, 0, 4, "red"});
values::Item item = palette.make("dot");
std::get<values::Dot>(item).x = 7;
const values::Item again = palette.make("dot");
LLD_CHECK_EQ(std::get<values::Dot>(again).x, 0);
}

Everything above exists because the code holds shapes through a base class pointer. When it does not, copying is just copying:

  • One known type. Code that has a Circle writes Circle copy = circle;. No clone() is needed when the type is known where the copy is made.
  • A small, closed set of types, all owned by one team: put plain structs in a std::variant.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

values.hpp
// Plain structs: every member copies itself, so `Dot copy = dot;` is a
// full, independent copy. No base class, no virtual functions.
struct Dot {
int x = 0;
int y = 0;
int radius = 1;
std::string colour;
};
struct Note {
int x = 0;
int y = 0;
std::string text;
};
// An Item holds exactly one of the listed types: a Dot or a Note. It is
// a value stored inside the Item itself, not a pointer to a separate
// object, so copying an Item copies whichever struct it holds.
using Item = std::variant<Dot, Note>; // adding a kind means editing this line
// The palette again, holding Items by value. No unique_ptr, no clone().
class Palette final {
public:
// try_emplace inserts only if the name is not in the map yet. It
// returns a pair; .second is true if it inserted and false if the
// name was already taken, and in that case nothing is stored and
// this throws std::invalid_argument.
void add(const std::string& name, Item preset) {
if (!presets_.try_emplace(name, std::move(preset)).second) {
throw std::invalid_argument{"preset '" + name + "' already exists"};
}
}
// A copy of the stored preset. Throws std::invalid_argument for an
// unknown name.
Item make(const std::string& name) const {
const auto found = presets_.find(name);
if (found == presets_.end()) {
throw std::invalid_argument{"no preset named '" + name + "'"};
}
return found->second; // a copy, because Item is a value
}
private:
std::map<std::string, Item> presets_;
};

Here make() returns a copy with return found->second;. There is no clone(), no separate heap object per shape, and no slicing, because a variant is a value. The last test above copies a preset and changes the copy, and the preset is unchanged.

The price is the opposite of Prototype’s. Adding a kind means editing the Item line and every std::visit that handles items, so FR-4 fails: another team cannot add a kind without changing this code. A group of items needs a recursive type: declare struct Group; first, put it in the Item variant, then define Group with a std::vector<Item> member. That works because, since C++17, std::vector accepts an element type that is not yet complete; every std::visit must then recurse into groups itself. Choose values when you own every kind; choose Prototype when kinds come from elsewhere, or when the copy must work on objects the program assembled from parts it cannot list in advance.

Use Prototype when:

  • code must copy objects it holds through a base class, and must not list the concrete classes;
  • the objects to copy are set up at run time (user presets, templates, a loaded document), so no constructor call in the code could make them;
  • other teams or plug-ins add new kinds, and copying must work for them without changes.

Prefer something simpler when:

  • the type is known where the copy is made: use the copy constructor;
  • you own every kind and the set is small: use value types in a std::variant;
  • the presets are fixed in code: a maker function per preset (Factory Method) is enough, and needs no clone() in every class.
  • Every concrete class writes clone(). It is one line, but a missing one in a non-final class slices silently (see the warning above).
  • Owning members need a hand-written deep copy, as in Group, and it must be kept in step when members are added.
  • At least one heap allocation per clone, plus one per child for a group (and the strings and vectors inside may allocate too). For a diagram editor this is negligible; for millions of small objects, value types are cheaper.
  • Copying a graph is harder than copying a tree. Children that point at each other (see “When the requirements change”) need more than clone() per object.
  • clone() where the type is known. auto c = circle.clone(); followed by a dynamic_cast<Circle&> is a slower, longer Circle c = circle;.
  • A shallow copy of owned parts. A group that holds std::shared_ptr children and relies on the default copy constructor shares its children with every copy; see the exercise.
  • clone() returning a raw pointer. Who deletes it is then unclear, and an exception between clone() and taking ownership leaks it. Return std::unique_ptr.
  • A public copy constructor or assignment on the base class. It makes slicing possible through every Shape&. Keep them protected or deleted.
  • Prototype as a way to avoid constructors. Cloning a default-made object and then changing half its members is harder to read than constructing the object with the right values, and the clone can skip the constructor’s checks if the setters do not repeat them.
  • “Copy and paste.” Copying a selection is cloning each selected shape; pasting into another document is placing those clones. Nothing new is needed.
  • “Arrows connect two shapes, and a group can contain both the arrow and its shapes.” Now a child points at its siblings, and cloning each child on its own gives a copied arrow that still points at the original shapes. The group’s copy must first clone the children, recording which new shape replaces which old one, then point each copied arrow at the new shapes. clone() per object is no longer enough; the group must copy the structure.
  • “Save presets to a file.” Prototype does not help with saving. Each kind needs a way to write itself out and be read back, and loading rebuilds the presets from data; once loaded, they are cloned as before.
  • “Change a preset, and every placed copy should follow.” That is the opposite of Prototype: the placed shapes should share the preset’s style, not copy it. Store a shared style object and have shapes refer to it; a Flyweight page, on sharing objects, is planned.

Exercise: Fix a shallow copy

A teammate writes a group that holds its children by std::shared_ptr, “so that the compiler writes the copy constructor”:

// A group whose children are held by std::shared_ptr instead of
// std::unique_ptr. No copy constructor is written: the compiler writes
// one, which copies the vector children_.
class SharedGroup final : public Shape {
public:
// Stores the child; std::move hands the caller's shared_ptr over.
void add(std::shared_ptr<Shape> child) { children_.push_back(std::move(child)); }
// The usual one-line clone(), which runs the compiler's copy
// constructor.
std::unique_ptr<Shape> clone() const override {
return std::make_unique<SharedGroup>(*this);
}
// Moves each child by (dx, dy).
void move_by(int dx, int dy) override {
for (const auto& child : children_) {
child->move_by(dx, dy);
}
}
std::string describe() const override; // the children's, joined by "; "
private:
std::vector<std::shared_ptr<Shape>> children_;
};

It compiles, and placing it from the palette appears to work.

  1. A user places a SharedGroup preset and moves it. What happens to the preset? Which requirement fails?
  2. Why did the compiler accept this class, when it refused to copy Group without a hand-written copy constructor?
  3. Fix it, keeping std::shared_ptr for the children.
  4. Write a test that would have caught the bug.
Show the explained answer

1. The preset moves too. The default copy constructor copies the vector of std::shared_ptr, and copying a shared_ptr copies the pointer, not the shape: the clone and the preset point at the same children. Moving the clone moves the shared children, so the preset, and every other copy placed from it, moves as well. This is a shallow copy, and FR-3 fails.

2. std::shared_ptr is copyable, so the compiler can write a copy constructor, and it does exactly what shared_ptr copying means: share. std::unique_ptr is not copyable, so for Group the compiler could not write one and made the author decide. Choosing shared_ptr “to get a copy constructor” silenced the question instead of answering it. Use shared_ptr only when sharing is the intended meaning.

3. Write the copy constructor, as Group does. A std::unique_ptr converts to a std::shared_ptr, so clone()’s result can be stored directly:

// Declaring any constructor, including a copy constructor, removes the
// default constructor the compiler would otherwise provide, so it is
// asked for back with "= default".
SharedGroup() = default;
// A hand-written deep copy, the same as Group's: every child is cloned,
// so the copy and the original share nothing. clone() returns a
// std::unique_ptr, and push_back turns it into a std::shared_ptr that is
// the only owner of the new child.
SharedGroup(const SharedGroup& other) : Shape{other} {
children_.reserve(other.children_.size());
for (const auto& child : other.children_) {
children_.push_back(child->clone()); // a new child, not a shared one
}
}

Declaring a copy constructor stops the compiler from providing the default constructor, hence SharedGroup() = default;. With the fix, shared_ptr no longer buys anything here; std::unique_ptr states the ownership more clearly.

4. Copy, change the copy, and check the original:

// Copy, change the copy, check the original. LLD_CHECK_EQ fails the test,
// printing both values, unless they are equal.
LLD_TEST(moving_a_cloned_shared_group_leaves_the_original) {
// A group with one circle at (0,0). After the copy is moved, the
// original's circle should still be at (0,0).
SharedGroup group;
group.add(std::make_shared<Circle>(0, 0, 1, "red"));
const auto copy = group.clone();
copy->move_by(5, 0);
LLD_CHECK_EQ(group.describe(), std::string{"red circle r1 at (0,0)"});
}

Before the fix, the original reads (5,0). The same “copy, change, check the original” test works for any class that claims to copy deeply.

  • Factory Method: a factory chooses a class in code; a prototype is a configured object that is copied. A registry of prototypes, like the palette, is a factory whose products can be added while the program runs. See Factory Method.
  • Abstract Factory: a family can be a set of prototypes, one per kind, cloned on request. See Abstract Factory.
  • Builder: copying a configured builder and changing a few parts is close to Prototype’s idea. See Builder.
  • Composite: Group is a composite, a shape made of shapes. Deep copying is one of the operations every composite must decide on. See Composite.
  • Prototype makes new objects by copying a configured one, through a virtual clone() that returns std::unique_ptr<Base>.
  • Each concrete class implements clone() with std::make_unique<Self>(*this); mark it final so a derived class cannot inherit a clone() that makes the wrong type.
  • An object that owns others copies them deeply, by cloning each one in its copy constructor. A std::shared_ptr member copies shallowly: the copies share.
  • Keep the base class’s copy constructor protected and its assignment deleted, so nothing slices.
  • When you know the type, or own a small, closed set of types, use plain value types instead.