TITLE: sideways and double casting (Newsgroups: comp.std.c++, 25 Feb 97) ???: >|> >(This leads to a further question: is a static_cast FROM void* legal? >|> >Should it be?) CLAMAGE: Stephen.Clamage@Eng (Steve Clamage) >|> Yes, since a static cast can reverse most implicit conversions. (I think >|> the only exception is reversing a conversion to a virtual base class.) >|> In particular, you can static_cast any data pointer to void* and back to >|> the original type and get a pointer that compares equal to the original. KANZE: kanze@gabi-soft.fr (J. Kanze) >This answers the first question. But should it be. Practically, it >means that static_cast can be used to cast between arbitrary pointer >types, since there is an implicit cast from any pointer type to void*, >which will allow the compiler to invoke the static cast. I don't think >that this is what the committee wanted, and IMHO, it breaks one of the >largest single reasons for the new cast syntax: a "sideways" cast within >a class hierarchy is no longer an error. CLAMAGE: I'm not sure what you are trying to say. You can't use static_cast to cast directly sideways in a hierarchy. That is, given class VB { ... }; class A : public virtual VB { ... }; class B : public virtual VB { ... }; class C : public A, public B { ... }; A* pa = new C; B* pb = static_cast(pa); // ERROR An old-style cast here would not result in an error message (it is treated as a reinterpet_cast under the new rules, and is quietly accepted under the old rules), but would not give a useful answer. The static_cast must yield an error. Isn't that what we want? You can write the "double cast" B* pb = static_cast(static_cast(pa)); which is perhaps your complaint. But programmers must be educated never to write code like this, just as they must be educated to avoid old-style casts: you can easily wind up with syntactically valid code with unknown or even undefined semantics. Safe casts in C++ may all be implicit. If you write an explicit cast, it should always be considered a flag that something unportable might be occuring. Many of the new-style casts are in fact safe if they compile. A "double cast", it seems to me, must always signal something dangerous and definitely unportable, even moreso than a reinterpret_cast. I think the only legitimate use for a "double cast" is when one of the pair is a const_cast, since the other three casts cannot remove constness. But removing const is in general dangerous, of course. You must somehow know that the object referred to is not really const.