Its probably something really dumb, but I do not understand the g++ output I am getting. I am trying to hold a pointer to a derived object to a virtual base class. When I run the commented code, it works fine and as expected, holding it in the unique_ptr does not compile.
Error message:
In file included from /usr/include/c++/4.9/memory:81:0,
from 2:
/usr/include/c++/4.9/bits/unique_ptr.h: In instantiation of 'typename std::_MakeUniq<_Tp>::__single_object std::make_unique(_Args&& ...) [with _Tp = base; _Args = {derived*}; typename std::_MakeUniq<_Tp>::__single_object = std::unique_ptr<base>]':
20:66: required from here
/usr/include/c++/4.9/bits/unique_ptr.h:765:69: error: invalid new-expression of abstract class type 'base'
{ return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
^
4:7: note: because the following virtual functions are pure within 'base':
6:18: note: virtual void base::foo()
7:18: note: virtual void base::bar()
Sample code
#include <memory>
class base {
public:
virtual void foo() = 0;
virtual void bar() = 0;
};
class derived : public base {
public:
derived() { }
void foo() override { printf("foo\n"); }
void bar() override { printf("bar\n"); }
void foobar() { printf("foobar\n"); }
};
int main()
{
std::unique_ptr<base> dv = std::make_unique<base>(new derived());
dv->foo();
reinterpret_cast<derived*>(dv.get())->foobar();
//base* dv = new derived();
//dv->foo();
//reinterpret_cast<derived*>(dv)->foobar();
}
I know it has to be some dumb error or a big missunderstanding from my part, but I found no solution when searching for virtual base classes with unique_ptr