Shared_ptr cannot find virtual method

I have an abstact base class that calls a virtual method in it. after passing the shared_ptrbase class, the implementation of the method was not found.

class a 
{
 public:
   a() { fill(); }
 protected:
   virtual void fill() = 0;
}

class b : public a
{
public:
   b() : a();
protected:
   virtual void fill() { // do something }
} 
....

shared_ptr<a> sptr = shared_ptr<a> ( new b()): // error happens here on runtime

When doing this, I get SIGABRT because it is trying to execute virtual void fill() = 0;

+4
source share
3 answers

You cannot call a pure virtual function from the constructor. At runtime, the constructor object is considered to be a constructed type, and not a derived type. This means that virtual dispatching "stops" when the type is built.

, fill() a a::fill(), - , a . , , , .


, @KerrekSB, . undefined, - delete a b a ( shared_ptr<a>).

UPDATE. -, shared_ptr , , . , , std::shared_ptr; - , ( ). .

+7

" "

std::make_shared:

shared_ptr<a> sptr = std::make_shared<b>();
+1

All Articles