Boost logo

Boost Users :

Subject: Re: [Boost-users] [smart pointer] need .get() to access derived class method?
From: Diederick C. Niehorster (dcnieho_at_[hidden])
Date: 2010-01-25 09:47:07


Hi Dominique,

That seems to have done the trick. Thank you for your lesson in
pointers, casting and boost's version of it.

I'll refer back to it and hope some others might find it useful as well.

Best,
Dee

On Mon, Jan 25, 2010 at 2:46 PM, Dominique Devienne <ddevienne_at_[hidden]> wrote:
> 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 mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
>


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