The difference between static_cast and dynamic_cast
// static_cast_Operator_2.cpp
// compile with: /LD /GR
class B {
public:
virtual void Test(){}
};
class D : public B {};
void f(B* pb) {
D* pd1 = dynamic_cast<D*>(pb);
D* pd2 = static_cast<D*>(pb);
}
// compile with: /LD /GR
class B {
public:
virtual void Test(){}
};
class D : public B {};
void f(B* pb) {
D* pd1 = dynamic_cast<D*>(pb);
D* pd2 = static_cast<D*>(pb);
}
if pb really points to an object of type D, then pd1 and pd2 will get the same value. They will get same value if pb = 0;
if pb points to an object of type B, then dynamic_cast will know enough to return zero. However, static_cast relies on the programmer's assertion that pb points to an object of type D and simple return a pointer to that supposed D object.
Consequently, static_cast can do the inverse of implicit conversions, in which case the results are undefined. It is left to the programmer to varify the results of a static_cast conversion are safe.