Here is an discussion on stackoverflow of the four kinds of explicitly cast. But I've come across a question in the most-voted answer.
Quoted from the most-voted wiki answer:
static_cast
can also cast through inheritance hierarchies. It is unnecessary when casting upwards (towards a base class), but when casting downwards it can be used as long as it doesn't cast throughvirtual
inheritance. It does not do checking, however, and it is undefined behavior tostatic_cast
down a hierarchy to a type that isn't actually the type of the object.
But in cppref,I read something less severely:
static_cast < new_type > ( expression )
If new_type is a pointer or reference to some class D and the type of expression is a pointer or reference to its non-virtual base B,
static_cast
performs a downcast. This downcast is ill-formed if B is ambiguous, inaccessible, or virtual base (or a base of a virtual base) of D. Suchstatic_cast
makes no runtime checks to ensure that the object's runtime type is actually D, and may only be used safely if this precondition is guaranteed by other means.
So in cppref it does not says undefined behavior,but instead less severely as not safe .
So when I do something like:
class A{virtual foo(){}};
class B:public A{};
class C:public B{};
int main()
{
C*pc=new C;
A*pa=static_cast<A*>(pc);//Ok,upcast.
B*pb=static_cast<B*>(pa);//downcast,**is it undefined or just not safe?**
C* pc1=static_cast<C*>(pb);//downcast back to C;
}
One more question,if it's not UB,is it UB to dereference pb
?