if so?:
class A { public: A(){a = 0;}; virtual ~A(){}; protected: int a; }; A *GetAInstance(); class B : public A { public: B() : A() {b = 1;}; virtual ~B(){}; protected: int b; }; class C: public B { public: C() : B() {}; ~C(){}; void CheckA() { A *pA = GetAInstance(); B *pB = dynamic_cast<B*>(pA); --> Here pB is NULL. B *pB2 = static_cast<B*>(pA); }; }; A *GetAInstance() { A *pA = new A(); return pA; }; int _tmain(int argc, _TCHAR* argv[]) { C *pC = new C(); pC->CheckA(); return 0; }
This is because you are trying to set the parent pointer to its child pointer. In dynamic_cast, he believes that it is unsafe, so he sets the child pointer to NULL, you can see pB above which is NULL. There can be more functions / member variables for a child class; you name these new functions / member variables will cause a runtime error. But static_cast does not care about this, it is only a compiler time check, not a runtime check. static_cast only cares if they have any ship relation. If they have, static_cast converts the pointer, do not even care about the runtime. Please run this small sample and check that pB2 is not NULL. :)
Hope helpful. Thank you :)
source share