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
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.)
This should work as stated originally. A derived_class* will happily cast down to a base_class* with which to construct the shared_ptr. As pointed out, ideone will compile it too. I suggest there is something wrong with your Boost installation or compiler.
Or, as pointed out, the rest of your code.
Type coercion is needed to be able to do this cast, which is implemented via a member template. This is not too well supported on older Compilers. Therefore it is disabled on these compilers. What compiler are you using?
精彩评论