Abstract Factory in C++

Level 5486 keystrokes

A factory function createShape chooses which Shape subclass to create from a string and returns it as unique_ptr<Shape>. The caller only uses the base-class interface, so draw() runs Circle's version.

C++ code

// Abstract base class for all shapes
1class Shape {
2public:
// Each shape must implement draw
3 virtual void draw() const = 0;
// Virtual destructor, needed because unique_ptr<Shape> deletes through the base type
4 virtual ~Shape() = default;
5};
6
7class Circle : public Shape {
8public:
// Circle's implementation of draw
9 void draw() const override { cout << "Drawing Circle" << endl; }
10};
11
12class Square : public Shape {
13public:
// Square's implementation of draw
14 void draw() const override { cout << "Drawing Square" << endl; }
15};
16
// Factory: the caller gets a Shape without knowing the concrete class
17unique_ptr<Shape> createShape(const string& type) {
// "circle" creates a Circle; unique_ptr<Circle> converts to unique_ptr<Shape>
18 if (type == "circle") return make_unique<Circle>();
// Any other string creates a Square
19 return make_unique<Square>();
20}
21
// auto is deduced as unique_ptr<Shape>
22auto shape = createShape("circle");
// Virtual call: prints "Drawing Circle"
23shape->draw();

Output

Drawing Circle
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • ;× 11
  • <× 11
  • (× 10
  • )× 10
  • "× 8
  • {× 6
  • }× 6
  • :× 5
  • =× 5
  • >× 4

More C++ examples at level 5

← C++ typing practice