Search code examples
c++castingshared-ptr

shared_pointer of a base class cannot be created using a polymorphic derived


I have a base polymorphic class ( with virtual methods ) and a derived from it. I am trying to use the following code

     boost::shared_ptr<base_class> ptr( new derived_class() );

but the compiler returns me the following error

    cannot convert ‘fpga_northwest*’ to ‘fpga*’ in initialization
    make: *** [../obj/ixecute_cmd_interface.o] Error 1

Reading a look around I am tempted to use the following that builds ok, but I have some doubts. Do you think that it is correct?

     boost::shared_ptr<base_class> ptr_base;
     boost::shared_ptr<derived_class> ptr_derived( new derived_class() );
     ptr_base = boost::dynamic_pointer_cast<base_class>( ptr_derived );

If I use a boost::static_pointer_cast I have compiler error; since I am casting from a derived to a base should not be more correct a static_cast?

Thanks for your help


Solution

  • boost::shared_ptr<base_class> ptr( new derived_class() );
    

    This should work just fine.

    Perhaps those classes are not related after all?

    Perhaps those classes are incomplete at that point, so the compiler doesn't know that the classes are related? (This should produce other error as well, though.)