Reputation:
Why does this small example:
class A {
public:
virtual void run() = 0;
};
class B : public A {
public:
void run() override {
std::cout << "Running...\n";
}
};
int main() {
std::unique_ptr<A> a = std::make_unique<A>(new B());
}
Gives me this error message:
error: invalid new-expression of abstract class type 'A'
{ return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
because the following virtual functions are pure within 'A':
class A {
'virtual void A::run()'
virtual void run() = 0;
Is this because a unique_ptr cannot take an abstract class as argument?
Upvotes: 4
Views: 10559
Reputation: 238351
Why does this small example: ... Gives me this error message:
invalid new-expression of abstract
Is this because a unique_ptr cannot take an abstract class as argument?
No, it isn't. std::unique_ptr
can take an abstract class as an argument.
It is because you're attempting to create an instance of A
. This is not possible because A
is abstract.
You may have intended instead to create an instance of B
, and have the std::unique_ptr<A>
take ownership of that pointer:
std::unique_ptr<A> a = std::make_unique<B>();
Note though however, that you mustn't let this pointer go out of scope, because upon destruction of a
, the object would be deleted through a pointer to A
, and since the pointed object is B
, and destructor of A
is not virtual, the behaviour would be undefined. Solution: declare A::~A
virtual.
Upvotes: 8