Re: Pointers to Members question
On Sep 24, 3:59 pm, "Victor Bazarov" <v.Abaza...@comAcast.net> wrote:
James Kanze wrote:
On Sep 21, 10:36 pm, "Victor Bazarov" <v.Abaza...@comAcast.net> wrote:
[...]
Generally speaking, a member of derived is NOT a member of base,
and that's why the conversion does not exist, and you have to resort
to some tricks (like casts) to silence the compiler that complains
otherwise. The static cast (as I understand it) would be called for
if you have a pointer to member of 'Base' ('Base::*ptr'), somehow
it was converted to a pointer to a member of 'Derived' ('Derived::*')
and then your base wants to call it. Then, since _originally_ the
pointer *was* to a member of 'Base', you're ok to use 'static_cast'.
If the pointer *never was* to a member of 'Base', casting is *not*
the right thing to do. You're correct suspecting that the behaviour
is undefined.
I think you've got it backwards. Pointer to member casts work
the opposite of normal pointer casts. There is an implicit D::*
to B::* conversion (no cast needed).
Nope. *You* got it backwards. Every member of 'B' is a member of
'D' as well (by inheritance), so 'B::*' ==> 'D::*' requires no special
syntax, its implicit (modulo all the "available" and "unambiguous"
cruft). [conv.mem]/2.
For the pointers to *objects*, however, it's reverse: Every 'D' is
a 'B' (modulo "available" and "unambiguous"), so conversion from 'D*'
to 'B*' is implicit.
Yes. There's a mix of misunderstanding what you wrote, and
mistyping what I wanted to say, there. What I wanted to say was
that the implicit conversions go in the opposite sense for
pointers to members, compared to pointers to objects (which you
just said in a lot clearer form), but that just like pointers to
objects, you can static_cast in the opposite sense of the
implicit conversion, *provided* the actual type is really a
derived; i.e. Base* -> Derived* is legal if the object pointed
to by Base* is actually a Derived, and Derived::* to Base::* is
legal if the resulting pointer to member is only used with the
address of a Base which is actually a Derived.
So you were wrong concerning undefined behavior. But to be
quite frank, I also thought it was undefined until I ran into a
large code base which used it.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34