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?
...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With