user3524337 user3524337 - 1 month ago 13
C++ Question

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

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

Base
and two derived classes --
A
and
B
. Instances of
Doer
class can choose between
A
's and
B
's methods
do()
. 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 {
public:
Doer(std::unique_ptr<Base> b_ptr) : ptr(b_ptr) {}
void do() const { ptr->do(); }
private:
std::unique_ptr<Base> ptr;
}

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

Answer

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>());