user3524337 user3524337 - 1 year ago 84
C++ Question

How to work with std::make_unique function and interface classes?

Suppose we want to implement strategy pattern. We have an interface

and two derived classes --
. Instances of
class can choose between
's and
's methods
. And the question is how to complete the code to make how it should be.

class Base {
virtual void do() const = 0;

class A: public Base {
void do() const override {};

class B: public Base {
void do() const override {};

class Doer {
Doer(std::unique_ptr<Base> b_ptr) : ptr(b_ptr) {}
void do() const { ptr->do(); }
std::unique_ptr<Base> ptr;

int main() {
Doer doer(std::unique_ptr<Base>());;
return 0;

Answer Source

There are three major problems with your code.

1) do is a keyword of the language. You cannot use it as an identifier (like function name)

2) you take b_ptr by value, so you need to move from it:

Doer(std::unique_ptr<Base> b_ptr) : ptr(std::move(b_ptr)) {}

3) you pass an empty unique_ptr to Doer's constructor, which is equivalent to passing a nullptr. You also try to instantiate the base class. It is impossible because Base is a pure virtual class. Use make_unique with a derived type:

Doer doer(std::make_unique<A>());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download