views:

271

answers:

3

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:).

A: 

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.

Will
+3  A: 

Try to use the search first old answer

ziggystar
Good pointer, though skip the accepted answer and delve right into the second one (by litb) which is right... unlike the first :/
Matthieu M.
@Mathieu: time fixed that, litb' answer is now first. Thanks for the hint anyway.
philippe
+1  A: 

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.

aJ
I suppose you meant Derived2* pDerCasted..?
lorenzog
yes, Derived2. I have updated.
aJ