Boost logo

Boost Users :

From: Sam Partington (sam.partington_at_[hidden])
Date: 2002-06-27 11:19:55


Not at all.

My guidelines for these things are (though I'm sure someone can pick
holes?):

class B {};
class D : public B{};

B* pB;
D* pD;

- pD will upcast to pB implicity.
- to cast from a pB to pD when I am absolutely sure that *pB is a *pD
        + use boost::polymorphic_downcast, if I have RTTI in this application (I
don't always have it available to me)
        + use static_cast if I don't have RTTI
- if I'm not absolutely sure that *pB is a *pD, then I use either :
        + dynamic_cast (if I want a null return value in case of failure) or
        + boost::polymorphic_cast (if I want an exception in case of failure)
- avoid casts wherever possible, prefer virtual functions to produce object
dependent behaviour
- use reinterpret_cast rarely, as a general rule I only use this when
dealing with a library that I have no control over,
- if I need to cross cast, rethink the whole design, do I really need to?

one final thing it that the above example won't actually work because
dynamic_cast requires a polymorphic source type, ie a class with at least
one virtual function, but I left out all functions for brevity. See Bjarne
15.4.

sam.

> -----Original Message-----
> From: news [mailto:news_at_[hidden]]On Behalf Of Jean Llorca
> Sent: 27 June 2002 16:45
> To: boost-users_at_[hidden]
> Subject: [Boost-Users] Re: Re: boost::polymorphic_upcast suggestion
>
>
> Thank you Sam,
>
> I feel quite shitty to not have known this before.
>
> I posted this because I thought static_cast couldn't "downcast"
> and because
> of downcast/upcast impairment. When I realized I could down_cast using
> reinterpret_cast and static_cast I should have reconsidered this
> instead of
> posting this thing.
>
> I learned C++ with visual:
> c:\dev\test\test.cpp(49) : error C2440: 'initializing' : cannot
> convert from
> 'class B *' to 'class C *'
> Types pointed to are unrelated; conversion requires
> reinterpret_cast, C-style cast or function-style cast
>
> If only the redactor could have added static_cast will do sometimes ;)
>
> Jean.


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