In the general case, it is (a very well deserved) Undefined Behavior to dowcast from a (dynamic) Base
to one of the deriving classes Derived
The obvious UB
class Base
{
public:
virtual void foo()
{ /* does something */?}
int a;
}
class Derived : public Base
{
public:
virtual void foo()
{ /* does something different */?}
double b;
}
Base obj;
Derived derObj = *static_cast<Derived *>(&obj); // <- here come the demons
In the current implementation approach of compilers, here there would obviously be at least the problems of inconsistent values in the Vtable and b containing garbage values. So it makes sense the standard does not define the behavior of a downcast in those conditions.
The not so obvious naive case
Yet I was curious to know if there were some concessions to this rule in specific cases ?
For an example :
class Base
{
public:
void foo()
{ /* does something */?}
int a = 1;
double b = 2.;
}
class DerivedForInt : public Base
{
int getVal()
{ return a }
}
Base obj;
DerivedForInt derObj = *static_cast<DerivedForInt *>(&obj); // <- still an UB ?
Here we can easily imagine compiler doing the right thing. But from the standard perspective, is it still undefined ?
Edit : static_cast is a random choice for illustration purpose, it is also interesting if working with other casts !
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…