What is dynamic casting in C ++

can anyone say what exactly is a means of dynamic casting in C ++. where exactly can we use this dynamic casting? It was suggested to me in an interview, and I went to this question :).

0
source share
3 answers

Try searching the old answer first

+2
source

dynamic_cast is a casting method to find out the class of an object 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. Generally, Dynamic_cast should be avoided with careful development of OO.

+8
source

.

This is achieved by creating compiler reference tables, which can be potentially quite large. For this reason, it is often disabled during compilation if the programmer knows that they are not using this function.

0
source

Source: https://habr.com/ru/post/1684971/


All Articles