what exactly is dynamic casting in c++ [duplicate]
can anyone tell what exactly is dynamic casting means in c++. where exactly can we use this dynamic casting? this was asked to me in the interview and i went blank for this question:).
dynamic_cast is casting method to find out the object's class at runtime.
class Base
{
public:
virtual bool func1();
};
class Derived1 : Base
{
public:
virtual bool func1();
virtual bool funcDer1();
};
class Derived2 : Base
{
public:
virtual bool func1();
virtual bool funcDer2();
};
Base* pDer1 = new Derived1;
Base* pDer2 = new Derived2;
Derived2* pDerCasted = dynamic_cast<Derived2*>(pDer2);
if(pDerCasted)
{
pDerCasted->funcDer2();
}
-> We cannot call funcDer2 with pDer2 as it points to Base class
-> dynamic_cast converts the object to Derived2 footprint
-> in case it fails to do so, it returns NULL .( throws bad_cast in case of reference)
Note: Usually, Dynamic_cast should be avoided with careful OO design.
Try to use the search first old answer
Dynamic casting is safely discovering the type of an object instance at runtime.
This is achieved by the compiler generating reference tables, which can be potentially rather large. For this reason, it is often disabled during compilation if the programmer knows that they do not use the feature.
精彩评论