Consider the following:

struct A; struct B : public A; struct C : public A; class Foo { public: void someFunction() { if( cond1 ) a = new B; if( cond2 ) a = new C; } private: A *a; // std::unique_ptr<A> a; };

Its easy and simple to use raw pointer here.

But is there a way to use smart pointer (std::unique_ptr) in this case? If yes - how? What syntax to use?

Please provide a way for C++11 and over.

wohlstad's user avatar

wohlstad

37k18 gold badges79 silver badges114 bronze badges

Igor's user avatar

8

Can I use unique_ptr with inherited classes

Yes.
std::unique_ptr supports using the pointer polymorphically, similarly to a raw pointer.
For C++11, you can initialize the smart pointer from a new B or new C.

This is demonstrated below:

#include <memory> #include <iostream> struct A { virtual ~A(){} // virtual destructor is required !!! virtual void do_something() {} }; struct B : public A { void do_something() override { std::cout << "B::do_something()\n"; } }; struct C : public A { void do_something() override { std::cout << "C::do_something()\n"; } }; class Foo { public: void someFunction(bool cond) { if (cond) { // Create a B: a = std::unique_ptr<A>(new B); } else { // Create a C: a = std::unique_ptr<A>(new C); } // Invoke a virtual method: a->do_something(); } private: std::unique_ptr<A> a; }; int main() { Foo foo; foo.someFunction(true); foo.someFunction(false); }

Output:

B::do_something() C::do_something()

Live demo 1.

If you can use C++14, there's a better option to initialize the smart pointer with std::make_unique:

a = std::make_unique<B>(); // or: a = std::make_unique<C>();

Live demo 2.

wohlstad's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.