Boost logo

Boost Users :

Subject: Re: [Boost-users] [smart pointer] need .get() to access derived class method?
From: Dominique Devienne (ddevienne_at_[hidden])
Date: 2010-01-25 01:46:38


On Sun, Jan 24, 2010 at 11:56 PM, Diederick C. Niehorster
<dcnieho_at_[hidden]> wrote:
> I have a base class, from which many classes are derived and I hold
> the derived class instance as a point of type baseclass. Usually, I
> only need access to the base class methods, but now i need to access
> some of the derived class's methods. How do I do that from a shared
> pointer?
> _pcStim = boost::shared_ptr<CStim>(new CStimUniform2D());

> ((boost::shared_ptr<CStimUniform2D>)(_pcStim))->setNPointGround()=300;
> ((CStimUniform2D*)pCStimU)->SetPointColor()=_pRoomData->dotColor();

In both cases above you use C-style casts, which is a bad idea because
they are unsafe. In C++, you use the new
(dynamic|static|const)_cast<T> operators instead. Boost extended this
idea by providing additional casts: the
(dynamic|static|const)_pointer_cast<T> template methods perform these
casts, and specializations exists for shared_ptr (as listed in the API
doc).

boost::shared_ptr<CStimUniform2D> pDerived =
boost::dynamic_pointer_cast<CStimUniform2D>(_pcStim);

Provided the cast you perform on the shared_ptr using
*_pointer_cast<T> is valid on the equivalent source and destination
raw pointers using *_cast<T*>, the boost pointer cast is also valid,
and will behave similarly. --DD


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net