Skip to content

Bridge

Difficulty: Advanced

Prerequisites

Key concepts

  • bridge pattern
  • abstraction and implementation
  • implementor interface
  • class explosion
  • PImpl idiom
  • compilation firewall
  • What the Bridge pattern is for: a design that varies in two independent ways, where one class per combination would multiply the classes.
  • How to split such a design into two hierarchies, the abstraction and the implementation, joined by one interface.
  • Why the hard part is designing that interface, and what it costs when one side needs something the interface does not offer.
  • The two ways to join the sides in C++: an implementation passed to each call, or one stored in the object.
  • How the PImpl idiom relates to Bridge, and the C++ rule it depends on.

A small diagram tool draws boxes, labelled badges, and the lines that connect them.

  1. FR-1 Draw three kinds of shape: a rectangle, a badge (a circle with a label in the middle), and a connector (a line with a dot at each end).
  2. FR-2 Write any drawing in two formats: SVG, for the web page, and plain text, one line per drawing step, for logs and for readers using a screen reader.
  3. FR-3 More of both are planned: a PDF format and a PNG format, and shapes such as arrows and diamonds. Adding one must not mean changing every existing class.
  4. FR-4 The geometry of each shape must be testable without parsing SVG.

Two things vary here, and they vary independently: which shape it is, and which format it is written in. Any shape can be written in any format.

Write one class for each shape in each format, all derived from a common Figure base with a render() function:

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

before.hpp
// A rectangle that can only be written as SVG. It derives from Figure, a
// small interface whose one job is `render()`: return the figure as text.
// The class name joins two separate facts, the shape (Rectangle) and the
// format (Svg), so every new shape or format needs new classes like it.
// `final` means no class may derive from this one.
class SvgRectangle final : public Figure {
public:
// Stores the top-left corner and the size. The `: name_{value}` list
// after the colon sets each member before the body runs; the body is
// empty, so nothing is checked: a zero or negative width is accepted.
SvgRectangle(Point top_left, int width, int height)
: top_left_{top_left}, width_{width}, height_{height} {}
// `override` says this replaces Figure's virtual render(), and makes
// the compiler check that such a function really exists in Figure.
std::string render() const override; // four <line> elements
private:
Point top_left_;
int width_;
int height_;
};
// The same rectangle again, written as plain text. Its data members are
// identical to SvgRectangle's; only render() differs. Nothing links the
// two classes, so a change to one has to be copied to the other by hand.
class TextRectangle final : public Figure {
public:
TextRectangle(Point top_left, int width, int height)
: top_left_{top_left}, width_{width}, height_{height} {}
std::string render() const override; // four "line" lines
private:
Point top_left_;
int width_;
int height_;
};

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

before.cpp
// Works out the four corners, then writes the four sides as SVG <line>
// elements, going round the rectangle: top, right, bottom, left. Each
// call to svg_line (a private helper earlier in this file) returns one
// line of SVG text between two corners, and `+` joins the four strings into one.
// In SVG, y grows downwards, so "y + height" is the bottom edge.
std::string SvgRectangle::render() const {
const Point a = top_left_; // top left
const Point b{a.x + width_, a.y}; // top right
const Point c{a.x + width_, a.y + height_}; // bottom right
const Point d{a.x, a.y + height_}; // bottom left
return svg_line(a, b) + svg_line(b, c) + svg_line(c, d) + svg_line(d, a);
}
// The text version. The first four lines are a copy of the geometry
// above; only the helper differs: text_line writes "line 0,0 to 40,0"
// instead of an SVG element. A change to how corners are worked out
// must be made in both functions, and in every future format's class.
std::string TextRectangle::render() const {
const Point a = top_left_; // the same corners, worked out again
const Point b{a.x + width_, a.y};
const Point c{a.x + width_, a.y + height_};
const Point d{a.x, a.y + height_};
return text_line(a, b) + text_line(b, c) + text_line(c, d) + text_line(d, a);
}

The badges and connectors follow the same plan: SvgBadge, TextBadge, SvgConnector, and TextConnector.

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

main.cpp
// The same rectangle twice, once per format: top-left corner (0, 0),
// 40 wide and 20 high. `{0, 0}` builds the Point argument in place.
// `before::` names the namespace the old classes live in, so they do
// not clash with the new ones. To draw one shape in two formats, the
// caller has to pick, and construct, two different classes.
const before::SvgRectangle svg_box{{0, 0}, 40, 20};
const before::TextRectangle text_box{{0, 0}, 40, 20};
std::cout << "before, SVG:\n" << svg_box.render();
std::cout << "before, text:\n" << text_box.render();

For two shapes and one format, this would be fine. Here it is already six classes, and the problems are visible:

  • The classes multiply. Three shapes in two formats need 3 × 2 = 6 classes. FR-3’s two new formats and two new shapes make 5 × 4 = 20.
  • Each class knows two things. SvgRectangle knows what a rectangle is (its four corners) and how SVG is written. So does every other class, for its own pair.
  • Knowledge is repeated. The corners of a rectangle are worked out in SvgRectangle and again in TextRectangle. A change to the geometry must be made once per format.
  • Fixes are repeated too, and get missed. SVG needs & and < escaped inside text (> is usually escaped too). Every SVG class that writes text must do that itself, and SvgBadge does not, so a label such as A&B makes invalid SVG. The test below shows it:

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, and LLD_CHECK(condition) records a
// failure if the condition is false. Both come from the site's small test
// header, lld_test.hpp.
//
// Sets up the same 4 x 2 rectangle at (0, 0) in both formats and proves
// that each class worked out the right-hand side, from corner (4, 0) to
// corner (4, 2), on its own. text.find(part) returns the position of `part`
// in the text, or std::string::npos ("not found"), so `!= npos` means "contains".
// The only way to check the geometry is to search each format's output.
LLD_TEST(before_each_format_repeats_the_geometry) {
// Each line builds a temporary rectangle, calls render() on it, and
// keeps only the string; the rectangle is destroyed straight after.
const std::string svg = before::SvgRectangle{{0, 0}, 4, 2}.render();
const std::string text = before::TextRectangle{{0, 0}, 4, 2}.render();
LLD_CHECK(svg.find("x2=\"4\" y2=\"2\"") != std::string::npos);
LLD_CHECK(text.find("line 4,0 to 4,2") != std::string::npos);
}
// Every SVG class that writes text must escape it itself; SvgBadge does not.
// This test passes because of the bug: it proves the raw "A&B" reaches the
// SVG output, where valid SVG would need "A&amp;B".
LLD_TEST(before_each_svg_class_must_remember_to_escape) {
const std::string svg = before::SvgBadge{{0, 0}, 3, "A&B"}.render();
LLD_CHECK(svg.find(">A&B<") != std::string::npos); // invalid SVG
}

FR-4 fails as well: the only way to test a rectangle’s corners is to search its SVG or text output.

Ask, for each piece of data and each job, which of the two things it is about:

Data or job About Where it goes
a rectangle’s corner, width, and height what the shape is Rectangle
a badge’s centre, radius, and label what the shape is Badge
a connector’s two ends what the shape is Connector
“a rectangle is four lines; a badge is a circle and text” what the shape is each shape’s draw
how a line, circle, or text is written in SVG, and the escaping the format SvgCanvas
how a line, circle, or text is written as plain text the format TextCanvas
the operations every format offers: line, circle, text both: the join the interface Canvas

Every row except the last belongs to exactly one side. The last row is the only thing the two sides share: a short list of drawing operations that every shape can be described with and every format can carry out. That list becomes an interface, and it is the bridge.

Bridge separates an abstraction from its implementation so that the two can vary independently. Instead of one class hierarchy for every combination, there are two hierarchies, and objects on one side use the other side only through an interface.

The words have a narrower meaning here than usual. The abstraction is the side the program’s other code works with: here, shapes. The implementation is the side that does the low-level work: here, output formats. Both sides are ordinary classes with virtual functions.

It has four participants:

  • The abstraction: the interface the rest of the program uses. Here, Shape.
  • The refined abstractions: its variants. Here, Rectangle, Badge, and Connector.
  • The implementor: the interface of low-level operations that the abstraction is written in. Here, Canvas.
  • The concrete implementors: one per platform, device, or format. Here, SvgCanvas and TextCanvas.
Two hierarchies: shapes draw using only Canvas, and each canvas writes one format
Text description of the diagram

A class diagram with two hierarchies. On the left, Shape is an interface with one pure virtual function, draw, which takes a Canvas reference. Rectangle, holding a top-left point, a width, and a height; Badge, holding a centre, a radius, and a label; and Connector, holding two points, each implement Shape. On the right, Canvas is an interface with three pure virtual functions: line, taking two points; circle, taking a centre and a radius; and text, taking a point and the words. SvgCanvas, which collects SVG elements and has a document function, and TextCanvas, which collects lines of text and has a str function, each implement Canvas. A dashed arrow from Shape to Canvas, labelled “draws on”, is the only connection between the two hierarchies: no shape knows any canvas class, and no canvas knows any shape.

Diagram source (Mermaid)
classDiagram
class Shape {
  <<interface>>
  +draw(Canvas&) void*
}
class Rectangle {
  -Point top_left_
  -int width_
  -int height_
  +draw(Canvas&) void
}
class Badge {
  -Point centre_
  -int radius_
  -string label_
  +draw(Canvas&) void
}
class Connector {
  -Point from_
  -Point to_
  +draw(Canvas&) void
}
class Canvas {
  <<interface>>
  +line(Point, Point) void*
  +circle(Point, int) void*
  +text(Point, string_view) void*
}
class SvgCanvas {
  -string elements_
  +document() string
}
class TextCanvas {
  -string out_
  +str() string
}
Shape <|.. Rectangle
Shape <|.. Badge
Shape <|.. Connector
Canvas <|.. SvgCanvas
Canvas <|.. TextCanvas
Shape ..> Canvas : draws on

The one arrow between the two hierarchies, labelled “draws on”, is the bridge. A new shape is added on the left and a new format on the right, and neither side changes:

Shapes Formats Concrete classes, one per combination Concrete classes with Bridge
3 2 6 3 + 2 = 5
5 4 20 5 + 4 = 9
10 5 50 10 + 5 = 15

For this page’s three shapes and two formats, Bridge saves one concrete class but adds a second interface (Shape and Canvas, where the before-version had only Figure), so there is no saving at all. The saving is not the main reason to use the pattern; FR-3 is. The pattern is worth its cost when both sides are expected to grow.

Before: one class per shape per format. After: one class per shape and one per format
Text description of the diagram

Before: six classes, SvgRectangle, TextRectangle, SvgBadge, TextBadge, SvgConnector, and TextConnector, each knowing one shape and one format. After: five classes. Rectangle, Badge, and Connector use the Canvas interface to draw, and SvgCanvas and TextCanvas implement it. Each class knows only one shape or only one format. The arrow from Before to After shows the refactoring on this page.

Diagram source (Mermaid)
flowchart LR
subgraph Before
  direction TB
  B1[SvgRectangle] ~~~ B2[TextRectangle]
  B3[SvgBadge] ~~~ B4[TextBadge]
  B5[SvgConnector] ~~~ B6[TextConnector]
end
subgraph After
  direction TB
  R[Rectangle] -. draws on .-> C[Canvas interface]
  G[Badge] -. draws on .-> C
  N[Connector] -. draws on .-> C
  S[SvgCanvas] -. implements .-> C
  T[TextCanvas] -. implements .-> C
end
Before --> After

The implementor lists the operations that shapes are drawn with:

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

canvas.hpp
// The implementation side of the bridge: the few things every output
// format can do. Shapes are drawn using only these.
// Each function is `virtual ... = 0` ("pure virtual"): Canvas gives no
// body, so it cannot be created on its own, and every concrete canvas
// must write all three. A call through a Canvas& runs the version of
// whichever canvas the reference really refers to. A Point is a small
// struct of two ints, x and y, so it is passed by value. The functions
// return nothing: a canvas keeps what it is given, and the code that
// created it reads the result out afterwards.
class Canvas {
public:
// Virtual, so that destroying a canvas through a Canvas pointer also
// runs the derived class's destructor.
virtual ~Canvas() = default;
virtual void line(Point from, Point to) = 0;
virtual void circle(Point centre, int radius) = 0;
// std::string_view is a read-only view of characters owned by the
// caller: no copy is made. A canvas that wants to keep the words must
// copy them before the call returns.
virtual void text(Point at, std::string_view words) = 0;
protected:
// Protected: only derived classes can use these. So code holding two
// Canvas references cannot assign one to the other, which would copy
// only the Canvas part and not the derived data ("slicing").
Canvas() = default;
Canvas(const Canvas&) = default;
Canvas& operator=(const Canvas&) = default;
};

This interface is the most important design decision on the page. It must be:

  • Enough for every shape. A rectangle is four lines, a badge is a circle and some text, and a connector is a line and two small circles. All three can be described with line, circle, and text.
  • Possible in every format. SVG has elements for all three, and plain text can describe all three in words. A planned PDF or PNG format can draw them too.
  • About drawing, not about shapes. There is no rectangle or badge function. If there were, every canvas would need a function for every shape, and the multiplication would be back inside Canvas.

The copy operations are protected, as on every interface on this site, so that a Canvas& cannot be copied and sliced, while derived classes stay copyable.

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

canvas.hpp
// Writes SVG elements; document() wraps them in an <svg> element.
// Each drawing call appends one element, on its own line, to elements_,
// in the order the calls arrive. text() escapes &, <, and > in the
// words, so every shape's text is made safe in this one place.
class SvgCanvas final : public Canvas {
public:
// `override` makes the compiler check that each of these really
// replaces a virtual function of Canvas.
void line(Point from, Point to) override;
void circle(Point centre, int radius) override;
void text(Point at, std::string_view words) override;
// Returns a new string: the elements so far inside <svg> ... </svg>.
// It does not clear them, so it can be called more than once.
// Not part of Canvas: only the code that made this canvas reads it.
std::string document() const;
private:
std::string elements_; // starts empty; each call adds one line
};
// Writes one plain-text line per drawing operation.
// The words are written unchanged: plain text needs no escaping.
class TextCanvas final : public Canvas {
public:
void line(Point from, Point to) override;
void circle(Point centre, int radius) override;
void text(Point at, std::string_view words) override;
// Returns a const reference to the text so far, without copying it.
// The reference is valid only while this canvas exists, and later
// drawing calls change the string it refers to.
const std::string& str() const { return out_; }
private:
std::string out_;
};

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

canvas.cpp
// Each function builds one SVG element as a string and appends it (+=)
// to elements_. number() is a private helper earlier in this file that
// turns an int into text (std::to_string). Inside a C++ string, \" is a
// double-quote character, which SVG needs round each attribute value.
// For example, line({0, 0}, {40, 0}) adds this line, two spaces in:
// <line x1="0" y1="0" x2="40" y2="0"/>
void SvgCanvas::line(Point from, Point to) {
elements_ += " <line x1=\"" + number(from.x) + "\" y1=\"" + number(from.y) + "\" x2=\"" +
number(to.x) + "\" y2=\"" + number(to.y) + "\"/>\n";
}
void SvgCanvas::circle(Point centre, int radius) {
elements_ += " <circle cx=\"" + number(centre.x) + "\" cy=\"" + number(centre.y) +
"\" r=\"" + number(radius) + "\"/>\n";
}
// The words go through svg_escaped (also earlier in this file), which
// copies them, replacing & with &amp;, < with &lt;, and > with &gt;, so
// a label such as "A&B" cannot break the SVG. This is the only place
// SVG text is written, so no shape can forget to escape.
void SvgCanvas::text(Point at, std::string_view words) {
elements_ += " <text x=\"" + number(at.x) + "\" y=\"" + number(at.y) + "\">" +
svg_escaped(words) + "</text>\n";
}
// Wraps everything drawn so far in an <svg> element. The xmlns
// attribute names the SVG standard, which browsers expect when an SVG
// file is opened on its own. const: reading out the document changes
// nothing, so it can be called again after more drawing.
std::string SvgCanvas::document() const {
return "<svg xmlns=\"http://www.w3.org/2000/svg\">\n" + elements_ + "</svg>\n";
}

SvgCanvas::text escapes the words, once, for every shape that will ever write text. In the before-version, each SVG class had to remember it. TextCanvas is written the same way, with one line of plain text per call.

Each canvas collects its output in a std::string and hands it out at the end (document() or str()). These functions are not in the Canvas interface: shapes do not read output, and each format’s result has its own type (a PNG canvas would produce bytes, not text), so only the code that created the canvas asks for it.

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

shapes.hpp
// The abstraction side of the bridge: what a shape is, in terms of the
// Canvas operations, with no knowledge of any output format.
// draw() is the bridge itself: a shape is handed a canvas and describes
// itself by calling line, circle, and text on it. The canvas is passed by
// reference (Canvas&), so the shape uses the caller's canvas, not a copy,
// and does not own it or keep it after draw returns. The copy operations
// are protected for the same reason as Canvas's: no slicing.
class Shape {
public:
virtual ~Shape() = default;
// Pure virtual (= 0): every shape must say how it is drawn. `const`:
// drawing does not change the shape. The canvas is not const, because
// drawing writes to it.
virtual void draw(Canvas& canvas) const = 0;
protected:
Shape() = default;
Shape(const Shape&) = default;
Shape& operator=(const Shape&) = default;
};

draw is const: drawing a shape does not change it. The canvas is not const, because drawing writes to it.

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

shapes.hpp
// The refined abstractions: one class per shape, each holding only its
// geometry. None of them mentions SVG or text.
// A rectangle given by its top-left corner and its size.
class Rectangle final : public Shape {
public:
// The exception it throws is std::invalid_argument, from <stdexcept>.
Rectangle(Point top_left, int width, int height); // throws unless both are positive
void draw(Canvas& canvas) const override; // four lines
private:
Point top_left_;
int width_;
int height_;
};
// A circle with a label in the middle.
class Badge final : public Shape {
public:
// The exception it throws is std::invalid_argument. The label is taken
// by value and moved into the member, so a caller passing a temporary
// string pays for no extra copy.
Badge(Point centre, int radius, std::string label); // throws unless radius is positive
void draw(Canvas& canvas) const override;
private:
Point centre_;
int radius_;
std::string label_;
};
// A line with a dot at each end. Any two points are accepted, even the
// same point twice, so there is nothing to check.
class Connector final : public Shape {
public:
Connector(Point from, Point to) : from_{from}, to_{to} {}
void draw(Canvas& canvas) const override;
private:
Point from_;
Point to_;
};
// Draws every shape in `shapes`, in order, on one canvas. The vector is
// read only (const&): draw_all neither copies it nor takes ownership of
// the shapes, which stay owned by the vector's unique_ptrs.
void draw_all(const std::vector<std::unique_ptr<Shape>>& shapes, Canvas& canvas);

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

shapes.cpp
// The four corners are worked out here, once, for every format. Then the
// four sides are drawn round the rectangle (top, right, bottom, left) by
// asking the canvas for four lines. Which format they come out in is up
// to the canvas: canvas.line(...) is a virtual call, so it runs
// SvgCanvas::line, TextCanvas::line, or a test's canvas, whichever was
// passed in. y grows downwards, so a.y + height_ is the bottom edge.
void Rectangle::draw(Canvas& canvas) const {
const Point a = top_left_; // top left
const Point b{a.x + width_, a.y}; // top right
const Point c{a.x + width_, a.y + height_}; // bottom right
const Point d{a.x, a.y + height_}; // bottom left
canvas.line(a, b);
canvas.line(b, c);
canvas.line(c, d);
canvas.line(d, a);
}
// A circle, then the label written at the same centre point. label_ is a
// std::string; it converts to the std::string_view that text() takes
// without copying, and the view stays valid because label_ outlives the
// call.
void Badge::draw(Canvas& canvas) const {
canvas.circle(centre_, radius_);
canvas.text(centre_, label_);
}
// The line between the two ends, then a dot of radius 1 on each end.
void Connector::draw(Canvas& canvas) const {
canvas.line(from_, to_);
canvas.circle(from_, 1);
canvas.circle(to_, 1);
}
// The loop knows only Shape and Canvas, so it works for every shape on
// every canvas. `const auto& shape` is a read-only reference to each
// unique_ptr in turn (a unique_ptr cannot be copied, so a reference is
// needed anyway). `->` calls draw on the shape the pointer owns, and the
// virtual call picks that shape's own draw.
void draw_all(const std::vector<std::unique_ptr<Shape>>& shapes, Canvas& canvas) {
for (const auto& shape : shapes) {
shape->draw(canvas);
}
}
How this code works: draw_all and the two virtual calls

Drawing one picture crosses the bridge once per drawing operation. Each crossing is a virtual call: the code calls a function through a reference or pointer to a base class, and the program runs the version belonging to the real object behind it.

  1. draw_all(shapes, svg) receives the vector of shapes by const reference and the canvas as a plain Canvas&. It does not know that the canvas is an SvgCanvas.
  2. The first virtual call: shape->draw(canvas). Each element is a std::unique_ptr<Shape>, so the loop only knows it has “some shape”. The call runs Rectangle::draw, Badge::draw, or Connector::draw, whichever the pointer really owns. This is what lets one loop handle every shape.
  3. The second virtual call: canvas.line(...), canvas.circle(...), or canvas.text(...). Inside a shape’s draw, the canvas is still only a Canvas&, so the call runs SvgCanvas::line or TextCanvas::line, whichever canvas was passed in. The shape decides what is drawn; the canvas decides how it is written.
  4. Nothing is copied or handed over. The shapes stay owned by the vector, and the canvas stays owned by the code that created it. Both are only borrowed for the length of the call, so draw_all has no lifetime to manage.

A worked example. The three shapes from main, drawn on an SvgCanvas:

Shape (from main) Calls its draw makes, in order Added to elements_
Rectangle at (0, 0), 40 × 20 line (0,0) to (40,0); (40,0) to (40,20); (40,20) to (0,20); (0,20) to (0,0) four <line> elements
Badge at (20, 10), radius 6, label A&B circle at (20,10), radius 6; text “A&B” at (20,10) a <circle>, then <text x="20" y="10">A&amp;B</text>
Connector from (40, 10) to (60, 10) line (40,10) to (60,10); circle at (40,10), radius 1; circle at (60,10), radius 1 a <line> and two <circle> elements

svg.document() then wraps those nine elements in one <svg> element. Drawing the same vector on a TextCanvas makes exactly the same nine calls, in the same order; only the text each call adds is different. Both results are shown under Check.

The rectangle’s corners are worked out once, in Rectangle::draw, for every format. The constructors check their arguments, so a shape that exists can always be drawn: a rectangle with no width, or a badge with no radius, is refused when it is made, not when it is written.

draw_all is a free function: it needs nothing private from any class, and it is the code a caller uses to draw a whole picture.

interface (abstract class) Canvas

the implementor

Member functions

  • virtual void line(Point from, Point to) = 0;
  • virtual void circle(Point centre, int radius) = 0;
  • virtual void text(Point at, std::string_view words) = 0;

class SvgCanvas final

a concrete implementor: SVG

Data members

  • std::string elements_;

Member functions

  • std::string document() const; the elements inside an <svg> element

class TextCanvas final

a concrete implementor: plain text

Data members

  • std::string out_;

Member functions

  • const std::string& str() const;

interface (abstract class) Shape

the abstraction

Member functions

  • virtual void draw(Canvas& canvas) const = 0;

class Rectangle final

a refined abstraction

Data members

  • Point top_left_;
  • int width_;
  • int height_;

Member functions

  • Rectangle(Point top_left, int width, int height); throws unless both are positive

class Badge final

a refined abstraction

Data members

  • Point centre_;
  • int radius_;
  • std::string label_;

Member functions

  • Badge(Point centre, int radius, std::string label); throws unless radius is positive

class Connector final

a refined abstraction

Data members

  • Point from_;
  • Point to_;

Member functions

  • Connector(Point from, Point to);

namespace global

not a real namespace: free functions at file scope

Functions

  • void draw_all(const std::vector<std::unique_ptr<Shape>>& shapes, Canvas& canvas);
The shape renderer: the Shape abstraction and its shapes, and the Canvas implementation interface and its canvases

The outline leaves out Point, a plain struct of two ints, and the draw and canvas overrides, which repeat the interfaces above.

  • The caller owns the shapes, in a std::vector<std::unique_ptr<Shape>>. A picture’s shapes are of different classes, so they are held through the base class, and the vector destroys them.
  • The caller owns each canvas, as an ordinary local variable.
  • A shape borrows a canvas only during draw. It takes a Canvas&, uses it, and keeps nothing. So there is no lifetime rule to state: when draw returns, the shape and the canvas are independent again.
  • In the stored form, there is a rule. If Shape held a Canvas*, every shape would have to be destroyed, or never used again, before its canvas. The usual way to keep that rule is to create the implementor first and the abstraction objects after it, in the same scope, so they are destroyed in the reverse order. If an abstraction owns its implementor outright, hold it in a std::unique_ptr and the question disappears.
  • Threads: drawing does not change a shape, so the same shapes can be drawn from several threads, each with its own canvas, as long as no thread changes the shapes or the vector at the same time. A canvas is not safe to share: each call appends to its string.

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

main.cpp
// One picture, built once. The vector owns its shapes: each
// std::unique_ptr<Shape> owns one shape on the heap and deletes it when
// the vector is destroyed at the end of main. Holding them through a
// pointer to the base class is what lets one vector hold a Rectangle,
// a Badge, and a Connector together. std::make_unique<Rectangle>(...)
// creates the object and passes the arguments to its constructor; the
// new pointer is a temporary, so push_back moves it into the vector.
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Rectangle>(Point{0, 0}, 40, 20));
shapes.push_back(std::make_unique<Badge>(Point{20, 10}, 6, "A&B"));
shapes.push_back(std::make_unique<Connector>(Point{40, 10}, Point{60, 10}));
// Draw the same shapes on an SVG canvas. The canvas is a local object;
// draw_all only borrows it (it takes a Canvas&), and the canvas keeps
// what was drawn until document() reads it out.
SvgCanvas svg;
draw_all(shapes, svg);
std::cout << "after, SVG:\n" << svg.document();
// And again on a plain-text canvas: no shape class changes, only the
// canvas passed in.
TextCanvas text;
draw_all(shapes, text);
std::cout << "after, text:\n" << text.str();
Expected output
before, SVG:
<line x1="0" y1="0" x2="40" y2="0"/>
<line x1="40" y1="0" x2="40" y2="20"/>
<line x1="40" y1="20" x2="0" y2="20"/>
<line x1="0" y1="20" x2="0" y2="0"/>
before, text:
line 0,0 to 40,0
line 40,0 to 40,20
line 40,20 to 0,20
line 0,20 to 0,0
after, SVG:
<svg xmlns="http://www.w3.org/2000/svg">
<line x1="0" y1="0" x2="40" y2="0"/>
<line x1="40" y1="0" x2="40" y2="20"/>
<line x1="40" y1="20" x2="0" y2="20"/>
<line x1="0" y1="20" x2="0" y2="0"/>
<circle cx="20" cy="10" r="6"/>
<text x="20" y="10">A&amp;B</text>
<line x1="40" y1="10" x2="60" y2="10"/>
<circle cx="40" cy="10" r="1"/>
<circle cx="60" cy="10" r="1"/>
</svg>
after, text:
line 0,0 to 40,0
line 40,0 to 40,20
line 40,20 to 0,20
line 0,20 to 0,0
circle at 20,10, radius 6
text at 20,10: A&B
line 40,10 to 60,10
circle at 40,10, radius 1
circle at 60,10, radius 1

Read the output against the requirements:

  • The same three shapes are written as SVG and as plain text (FR-1, FR-2), from one vector of shapes and two canvases.
  • The first four <line> elements inside the <svg> element after “after, SVG:” are the same as the four lines after “before, SVG:”, and the same is true for the text format, so the refactoring changed no output for the rectangle.
  • The badge’s label A&B comes out as A&amp;B in SVG and unchanged in plain text. The escaping lives in SvgCanvas, so no shape can forget it.

FR-4 is met with a third canvas, written only for the tests. It records each call, so a test can check a shape’s geometry without any real format:

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

test_shapes.cpp
// A canvas that records each call, so shapes can be tested without any
// real output format.
// It is a third implementor, written only for the tests. Each drawing
// call appends one short string to `calls`, such as "line 1,2 5,2" or
// "circle 5,5 2", so a test can compare the whole list of calls, in order,
// with the list it expects. `calls` is public so the tests can read it.
class RecordingCanvas final : public Canvas {
public:
void line(Point a, Point b) override { calls.push_back("line " + at(a) + " " + at(b)); }
void circle(Point c, int r) override { calls.push_back("circle " + at(c) + " " + std::to_string(r)); }
void text(Point p, std::string_view words) override {
calls.push_back("text " + at(p) + " " + std::string{words});
}
std::vector<std::string> calls;
private:
// Turns a point into "x,y" text, for example Point{1, 2} into "1,2".
// static: it uses no member of the canvas.
static std::string at(Point p) { return std::to_string(p.x) + "," + std::to_string(p.y); }
};

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

test_shapes.cpp
// static_assert is checked by the compiler, not when the tests run: if the
// condition is false, the file does not compile. std::is_abstract_v<T> is
// true for a class with a pure virtual function, which cannot be created
// on its own. So neither interface can be used as a finished class.
static_assert(std::is_abstract_v<Shape> && std::is_abstract_v<Canvas>);
// Draws a rectangle with its top-left corner at (1, 2), 4 wide and 3 high,
// and proves it is exactly four lines round its corners (1,2), (5,2),
// (5,5), (1,5), in that order: 1 + 4 = 5 across and 2 + 3 = 5 down.
LLD_TEST(a_rectangle_is_four_lines_round_its_corners) {
RecordingCanvas canvas;
// A temporary Rectangle, drawn once onto the canvas, then destroyed.
Rectangle{{1, 2}, 4, 3}.draw(canvas);
const std::vector<std::string> expected{"line 1,2 5,2", "line 5,2 5,5", "line 5,5 1,5",
"line 1,5 1,2"};
LLD_CHECK(canvas.calls == expected);
}
// Draws a badge and then a connector onto one recording canvas, and proves
// that both are made from the same three operations, in the order each
// draw() makes them: the badge's circle and text, then the connector's line
// and its two radius-1 dots.
LLD_TEST(a_badge_and_a_connector_use_the_same_operations) {
RecordingCanvas canvas;
Badge{{5, 5}, 2, "hi"}.draw(canvas);
Connector{{0, 0}, {9, 0}}.draw(canvas);
const std::vector<std::string> expected{"circle 5,5 2", "text 5,5 hi", "line 0,0 9,0",
"circle 0,0 1", "circle 9,0 1"};
LLD_CHECK(canvas.calls == expected);
}
// Calls text() straight on an SVG canvas, with no shape at all, and proves
// that &, <, and > come out escaped. Because every shape writes text through
// this one function, testing it here covers every shape.
// LLD_CHECK_EQ(actual, expected) fails unless the two are equal, and on
// failure prints both values. Two string
// literals written next to each other are joined into one by the compiler.
LLD_TEST(the_svg_canvas_escapes_text_for_every_shape) {
SvgCanvas svg;
svg.text({0, 0}, "A&B <c>");
LLD_CHECK_EQ(svg.document(), std::string{"<svg xmlns=\"http://www.w3.org/2000/svg\">\n"
" <text x=\"0\" y=\"0\">A&amp;B &lt;c&gt;</text>\n"
"</svg>\n"});
}
// Builds a one-shape picture (a connector from (0, 0) to (3, 0)) and draws
// the same vector on both real canvases: the text canvas must give exactly
// three lines, and the SVG document must contain the connector's <line>.
LLD_TEST(both_canvases_draw_the_same_shapes) {
std::vector<std::unique_ptr<Shape>> shapes;
shapes.push_back(std::make_unique<Connector>(Point{0, 0}, Point{3, 0}));
TextCanvas text;
draw_all(shapes, text);
LLD_CHECK_EQ(text.str(), std::string{"line 0,0 to 3,0\n"
"circle at 0,0, radius 1\n"
"circle at 3,0, radius 1\n"});
SvgCanvas svg;
draw_all(shapes, svg);
LLD_CHECK(svg.document().find("<line x1=\"0\" y1=\"0\" x2=\"3\" y2=\"0\"/>") !=
std::string::npos);
}
// Draws the same 4 x 2 rectangle with the new classes and the old ones, and
// proves the outputs are identical. The old SVG class writes only the four
// <line> elements, so the expected document is that text wrapped in the
// same <svg> opening and closing lines that document() adds.
LLD_TEST(the_after_version_matches_the_before_version) {
const Rectangle box{{0, 0}, 4, 2};
const std::string old_svg = before::SvgRectangle{{0, 0}, 4, 2}.render();
const std::string old_text = before::TextRectangle{{0, 0}, 4, 2}.render();
SvgCanvas svg;
box.draw(svg);
LLD_CHECK_EQ(svg.document(), "<svg xmlns=\"http://www.w3.org/2000/svg\">\n" + old_svg + "</svg>\n");
TextCanvas text;
box.draw(text);
LLD_CHECK_EQ(text.str(), old_text);
}
// LLD_CHECK_THROWS(expression, type) fails unless evaluating the expression
// throws an exception of that type. Here each expression only constructs a
// shape: a zero width, a negative height, and a zero radius must each be
// refused with std::invalid_argument.
LLD_TEST(shapes_refuse_sizes_that_cannot_be_drawn) {
LLD_CHECK_THROWS(Rectangle({0, 0}, 0, 5), std::invalid_argument);
LLD_CHECK_THROWS(Rectangle({0, 0}, 5, -1), std::invalid_argument);
LLD_CHECK_THROWS(Badge({0, 0}, 0, "x"), std::invalid_argument);
}
  • The first two tests check each shape’s drawing steps through the recording canvas, in the order they are made.
  • the_svg_canvas_escapes_text_for_every_shape checks the escaping once, on the canvas, rather than once per shape.
  • both_canvases_draw_the_same_shapes draws one connector on both real canvases from the same vector.
  • the_after_version_matches_the_before_version draws a rectangle on both real canvases and compares the result with the before-version’s output, so the refactoring is checked by a test as well as by reading the output.
  • shapes_refuse_sizes_that_cannot_be_drawn checks the constructors.
  • The static_assert checks that both Shape and Canvas are abstract.

That the tests can use a recording canvas at all is a sign that the split is right: the shapes really do depend only on Canvas.

The SVG is minimal: it has no stroke colours, line widths, or fonts. Without a stroke attribute, a browser draws the lines invisibly and the circles as filled black discs. No canvas measures text, and the SVG label starts at the badge’s centre rather than being centred on it; centring needs text-anchor="middle", which Canvas::text cannot ask for. Positions are whole numbers. A real renderer would need more in Canvas, such as a style for each line, and every new operation is a cost on the implementation side (see Costs).

C++ programmers often meet a one-sided version of this idea first, as the PImpl idiom (“pointer to implementation”). A class keeps all its data members in a separate struct that only its .cpp file defines, and holds a pointer to it:

report.hpp
#include <memory>
#include <string>
#include <string_view>
// A report made of lines of text. Users see only these functions; the
// data members live in Impl, which this header only names. Report owns
// its Impl through a unique_ptr, so it can be moved but not copied (the
// copy operations are not declared, and unique_ptr cannot be copied).
class Report final {
public:
Report(); // creates an empty Impl
~Report(); // defined where Impl is complete
// Move constructor and move assignment (the && means "from an object
// that is being moved from"). Only declared here, for the same reason
// as the destructor. A moved-from Report holds a null impl_, so the
// only safe things to do with it are to destroy it or assign to it.
Report(Report&&) noexcept;
Report& operator=(Report&&) noexcept;
void add_line(std::string_view line); // stores a copy of the line
std::string str() const; // every line, each ending "\n"
private:
// A forward declaration: "a struct called Impl exists". Its members are
// unknown here (an incomplete type), but a pointer to it is allowed.
struct Impl; // defined only in report.cpp
std::unique_ptr<Impl> impl_; // owns the Impl; deletes it
};
report.cpp
#include "report.hpp"
#include <string>
#include <vector>
// The real data. Only this file sees it, so only this file needs
// <vector>, and only this file is recompiled when the members change.
struct Report::Impl {
std::vector<std::string> lines;
};
// Each Report allocates its own Impl on the heap.
Report::Report() : impl_{std::make_unique<Impl>()} {}
// "= default" asks the compiler to write the usual body. Written here,
// where Impl is complete, the generated code can call Impl's destructor
// through unique_ptr. A move just hands the Impl pointer over to the new
// Report; no lines are copied.
Report::~Report() = default;
Report::Report(Report&&) noexcept = default;
Report& Report::operator=(Report&&) noexcept = default;
// impl_-> reaches the Impl the pointer owns. emplace_back(line) builds a
// new std::string from the string_view, directly at the end of the vector.
void Report::add_line(std::string_view line) { impl_->lines.emplace_back(line); }
// Joins the lines, adding a newline after each one.
std::string Report::str() const {
std::string out;
for (const std::string& line : impl_->lines) {
out += line + "\n";
}
return out;
}

Code that includes report.hpp never sees Impl, so it does not need <vector>, and a change to Impl’s members recompiles only report.cpp. This is often called a compilation firewall.

How it relates to Bridge. The structure is the same: the class people use holds a pointer to a separate implementation. The purpose is different:

Question Bridge PImpl
How many implementations? several, chosen by the caller exactly one, hidden
Is there an interface? yes, with virtual functions no: Impl is a plain struct
Why use it? two things vary independently hide private details from the header: shorter builds, fewer recompiles
Who can add a variant? anyone, by implementing the interface nobody outside report.cpp

The classic description of Bridge treats this as a degenerate Bridge: one implementation, no implementor interface, kept separate so that changing it does not affect the class’s users. It is still worth keeping the two ideas apart: a full Bridge is about two things varying, and PImpl is about build times and hiding details. Use it for a class that is included in many files and whose private members change often. Do not use it to make a class “more designed”: it costs a heap allocation per object and an extra indirection on every call.

Three more points if you write one:

  • Copying is not automatic. std::unique_ptr cannot be copied, so Report is move-only. If it must be copyable, write a copy constructor and a copy assignment operator, both in the .cpp file, that make a new Impl from *other.impl_.
  • A moved-from object has no Impl. After a move, impl_ is null, so calling add_line or str on the moved-from Report is undefined behaviour unless those functions check for null. Treat a moved-from Report as usable only for assignment or destruction.
  • const does not reach the Impl. In str() const, the pointer impl_ is const, but the Impl it points to is not, so impl_->lines.clear() would compile. The compiler will not catch that mistake; review const member functions with care.

PImpl, ABI, versioning, and compatibility shows why it matters for shared libraries.

  • The design varies in two independent ways, and both are expected to grow: shapes and formats, messages and delivery channels, reports and storage back ends, controls and operating systems.
  • The low-level side must be swappable at run time or per object, such as drawing the same picture on the screen and to a file.
  • The low-level side must be testable on its own, or the high-level side must be testable without it, as the recording canvas shows.
  • The implementor interface is clear: a small set of operations that every implementation can provide and every abstraction can be written with.
  • Only one thing varies. If there will only ever be one format, a Shape hierarchy that writes SVG directly is simpler. If there is only one shape and many formats, a plain interface for the format, with no abstraction hierarchy, is enough. That is closer to Strategy.
  • No common operations exist. If each format needs to know which shape it is drawing, for example because PDF has a native rectangle that must be used, the implementor interface turns into one function per shape, and the split buys nothing.
  • The classes already exist and do not fit. Joining two existing interfaces after the fact is Adapter. Bridge is designed in, usually before both sides are fully written.
  • Speculatively. “There might be a second format one day” is not FR-3. Two hierarchies and an interface for one shape and one format is unnecessary abstraction.
  • Two hierarchies and an interface, which a reader must hold in their head together. A reader of Rectangle::draw cannot see what the output looks like without reading a canvas.
  • The implementor interface is the narrowest point. Everything the shapes can express must go through it. A format’s special abilities, such as SVG’s rounded corners or PDF’s native rectangles, are not used unless the interface grows.
  • Growing the implementor interface touches every implementation. A new Canvas function, such as curve, must be written in every canvas, including the test ones. A default implementation in Canvas (drawing a curve as short lines, say) softens this, but only if the default is acceptable for every format.
  • A virtual call per drawing step. For a diagram tool this is too small to measure; for drawing millions of points it may matter, and should be measured.
  • An implementor interface named after the abstractions. A Canvas with draw_rectangle, draw_badge, and draw_connector puts every shape into every canvas: the class explosion has moved, not gone.
  • Each side knowing the other’s variants. A shape that checks dynamic_cast<SvgCanvas*> to use an SVG feature joins the hierarchies again. If the feature matters, add it to Canvas with a sensible default.
  • Bridge for one dimension. Two hierarchies where one has a single class are an interface with extra steps.
  • Expecting PImpl to give Bridge’s flexibility. PImpl hides one implementation to speed up builds; it does not let anything vary.
  • “Add a PDF format.” Write PdfCanvas, implementing Canvas. No shape changes, and every shape, including ones written later, can be drawn in PDF.
  • “Add an arrow shape.” Write Arrow, implementing Shape in terms of line. No canvas changes, and the arrow can be drawn in every format.
  • “Add rounded rectangles.” If they can be drawn with the existing operations, only a new shape is needed. If they need a new operation, such as an arc, Canvas grows, and so does every canvas: the cost described above.
  • “Group shapes so they move together.” A group of shapes that is itself a shape is the Composite pattern. It fits on the abstraction side, and the canvases do not change.

Exercise: Add a renderer without adding classes per shape

The diagram tool needs to know how much room a picture takes before it lays out the page: the smallest box, with sides parallel to the axes, that contains everything drawn.

  1. Add this without changing Shape, Rectangle, Badge, Connector, or draw_all. Return no box when nothing has been drawn.
  2. What do the three shapes from main give?
  3. How many classes would the one-class-per-combination design need to add for the same feature, and what would each repeat?
  4. What is your answer’s weakest part?
Show the explained answer

1. The bounds are a new implementation: a canvas that, instead of writing output, widens a box to include each point drawn.

// A box with sides parallel to the axes: min is its top-left corner (the
// smallest x and y), max its bottom-right corner (the largest x and y).
struct Box {
Point min;
Point max;
};
// A canvas that writes nothing. Each drawing call only grows a box so that
// it contains the points drawn. The shapes cannot tell the difference: to
// them it is just another Canvas.
class BoundsCanvas final : public Canvas {
public:
// A straight line between two points stays inside any box that holds
// both ends, so the ends are enough.
void line(Point from, Point to) override {
include(from);
include(to);
}
// The smallest box round a circle has corners at centre - radius and
// centre + radius on both axes. `{x, y}` builds the Point argument.
void circle(Point centre, int radius) override {
include({centre.x - radius, centre.y - radius});
include({centre.x + radius, centre.y + radius});
}
// The words have no name: this canvas does not use them.
void text(Point at, std::string_view) override { include(at); } // a point only: no font sizes
// A copy of the box, or an empty optional if nothing was drawn.
std::optional<Box> bounds() const { return box_; }
private:
// Grows the box, if needed, so that it contains the point.
void include(Point p) {
// No box yet: the first point is the whole box, both corners at it.
if (!box_) {
box_ = Box{p, p};
return;
}
// Otherwise widen each side the point lies beyond. box_-> reaches the
// Box inside the optional; it is safe because box_ was just checked.
box_->min = {std::min(box_->min.x, p.x), std::min(box_->min.y, p.y)};
box_->max = {std::max(box_->max.x, p.x), std::max(box_->max.y, p.y)};
}
std::optional<Box> box_; // starts empty: "nothing drawn yet"
};

Use it like any other canvas: BoundsCanvas bounds; draw_all(shapes, bounds);, then read bounds.bounds(). std::optional says “no box yet” without inventing a special value.

2. From 0,0 to 61,20. The rectangle covers 0,0 to 40,20; the badge, centre 20,10 and radius 6, stays inside it; the connector’s dot at 60,10 has radius 1, so it reaches x = 61. (This answer was compiled and run against the example’s shapes with GCC and Clang.)

3. Three: BoundsRectangle, BoundsBadge, and BoundsConnector, each working out its shape’s geometry yet again, so a rectangle’s corners would then be in three places. With Bridge, it is one class, and every future shape gets bounds for free.

4. Text. The canvas includes only the point where the text starts, because Canvas::text gives no font or size, so a long label that sticks out of its badge is not counted. Fixing it needs more information through the implementor interface, such as a font size, which every canvas would then receive: the cost of a narrow interface, seen from the other side.

  • Adapter makes an existing class fit an interface it was not written for, after the fact; Bridge separates two hierarchies on purpose, before they grow. See Adapter and Adapter vs Bridge.
  • Strategy also passes an object behind an interface, and a single canvas passed to one function looks like a Strategy. The difference is the second hierarchy: Strategy swaps one algorithm inside one class, while Bridge lets a whole family of abstractions use a whole family of implementations. See Strategy.
  • Abstract Factory can create the right implementor for a platform, once, at start-up. Its concrete products are one class per kind per family, the same grid Bridge avoids; when the products can be written with a common set of low-level operations, Bridge can replace that grid. See Abstract Factory.
  • Composite would add groups of shapes on the abstraction side. See Composite.
  • PImpl uses Bridge’s shape, with one hidden implementation, to shorten builds. See above; a full page is planned.
  • Use Bridge when a design varies in two independent ways, and one class per combination would multiply the classes and repeat their knowledge.
  • Split it into an abstraction hierarchy and an implementation hierarchy. The abstraction is written only in terms of the implementor interface.
  • Design that interface carefully: small, possible for every implementation, enough for every abstraction, and named after operations, not after the abstractions.
  • In C++, pass the implementor to each call when the same objects are used with several implementations; store it when each object belongs to one implementation, and state the lifetime rule.
  • PImpl has the same shape for a different reason: hiding one implementation from the header. Declare its destructor in the header and define it in the .cpp file.