We haveWhy the complie needs Base class has at least a virtual method?Code:class Derived : public Base{ }; int main(){ Base* b = new Base; Derived * d = dynamic_cast< Derived *>(b); return 1; }
We haveWhy the complie needs Base class has at least a virtual method?Code:class Derived : public Base{ }; int main(){ Base* b = new Base; Derived * d = dynamic_cast< Derived *>(b); return 1; }
Derived * d = new Derived;
Base* b = dynamic_cast<Base*>(d);
//no problem
//no virtual function needed in class Base
When a class has virtual functions, there are certain pieces of special runtime data created for objects of that class. When downcasting, dynamic_cast<> needs this data in order to do what it does.
In this example, you're upcasting. This is equivilant to a static_cast<>, so no virtuals are needed.Code:Derived * d = new Derived; Base* b = dynamic_cast<Base*>(d); //no problem //no virtual function needed in class Base
There is no greater sign that a computing technology is worthless than the association of the word "solution" with it.
Could you give me an example that using dynamic_cast to downcast and return value is not NULL?
There is no greater sign that a computing technology is worthless than the association of the word "solution" with it.
Example
Code:#include <iostream> class CBaseClass { public: virtual void SayHello(){ std::cout<<"Hello From The Base"<<std::endl; } }; class CChildClass : public CBaseClass { public: virtual void SayHello(){ std::cout<<"Hello From The Child"<<std::endl; } }; int main() { CBaseClass *pBaseChild = new CChildClass; CChildClass *pChild = NULL; //This is a correct cast since pBaseChild is actally a child class pChild = dynamic_cast<CChildClass*>(pBaseChild); if(NULL != pChild){ pChild->SayHello(); }//if else{ std::cout<<"Child Was NULL"<<std::endl; }//else CBaseClass *pBaseBase = new CBaseClass; CChildClass *pChildTwo = NULL; //This is an invalid cast because pBaseBase is actually a base class pChildTwo = dynamic_cast<CChildClass*>(pBaseBase); if(NULL != pChildTwo){ pChildTwo->SayHello(); }//if else{ std::cout<<"Child Two was NULL"<<std::endl; }//else //Clean up delete pBaseChild; delete pBaseBase; std::cin.get(); return 0; }
Woop?
Your example needs a virtual destrctor in the base class, prog-bman.