Re: static_cast
On Sep 14, 10:27 pm, Rahul <rahulsha...@lucent.com> wrote:
Everywhere I read that static_cast<> only work fine for the
conversion which are implicitly allowed by the compiler
Where's everywhere. I've never read that.
As a very rough first approximation, static_cast can be used
where ever the converision or its inverse would be implicitly
allowed, and const-ness is preserved.
hence the following does not work
int *i;
double *d;
d = i; // Compilation error ,
OK
i= static_cast<int *>(d); // Compilation error. OK
Since the two pointers are to unrelated types, there is no
conversion in either direction, and the static cast is
forbidden. static_cast< void* >( d ) is legal, however (since
there is an implicite conversion double* to void), as if
static_cast< double* >( ptrToVoid ), since this is the inverse
of an implicite conversion (and doesn't affect const-ness).
But surprisingly the following static_cast from Base * to
Derived * works (assume class Derived: public Base)
Base *bp=new Base();
Derived *dp=new Derived();
bp= dp; // Error, compiler does not allow this, This is OK
dp=static_cast<Derived*> (bp); // COMPILES FINE. But why does
compiler allow this (I tested in VC++ and gcc)
Because there is an implicit conversion Derived* to Base*, and
you're not removing const. (Also because this particular case
is spelled out explicitly in the standard. In fact, all of the
cases are more or less spelled out explicitly, since it isn't
sufficient for the standard to say that the cast is legal; it
also has to specify its semantics.)
--
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