Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::shared_ptr and assigning derived classes

Assume DerivedClass is derived from BaseClass
Would the following work?

boost::shared_ptr<BaseClass> a(new BaseClass());
boost::shared_ptr<DerivedClass> b(new DerivedClass());
a=b;

Following this question, I understand that now a points to the derived and b points to the base (right?)

Also, now if I call a function via a would it call the derived implementation?

like image 225
Jonathan Livni Avatar asked Feb 27 '11 15:02

Jonathan Livni


1 Answers

...
a=b;

You are reassigning to a and therefore a and b would now both point to the DerivedClass object. The BaseClass object would be destroyed, since its reference count would be zero at this point (by virtue of a being reasigned to point to a different object).

Since a now points to a DerivedClass object, virtual function calls (defined in BaseClass and overriden in DerivedClass) via a would call the corresponding member functions in DerivedClass.

When both a and b go out of scope, the DerivedClass object would be destroyed.

If you need to access functions specific to the derived class via a (e.g., non-virtual functions in DerivedClass), you can use:

boost::dynamic_pointer_cast<DerivedClass>(a)->SomeFunctionOnlyInDerivedClass();

Of course this is just a terse example that shows usage. In production code, you would almost certainly test for a successful cast to the DerivedClass, before dereferencing the pointer.

like image 67
Michael Goldshteyn Avatar answered Oct 02 '22 23:10

Michael Goldshteyn