C++ – Do I need to use dynamic_cast when calling a function that accepts the base class

c++-clidynamic-castfunction

I have some classes like this:

interface class IA
{
};

interface class IB
{
};

public ref class C : public IA, public IB
{
};

public ref class D
{
    void DoSomething(IA^ aaa)
    {
    }

    void Run()
    {
        C^ bob = gcnew C();
        DoSomething(dynamic_cast<IA^>(bob));    // #1
        DoSomething(bob);           // #2
    }
};

At the moment I always try to use dynamic casting when calling such a function, (the #1 above).
However it does make the code quite ugly, so I want to know if it is actually necessary.

Do you use dynamic_cast in this way? If so what is the main reason?

Best Answer

In standard C++, you use dynamic_cast to walk down the hierarchy, not up. In this case, you'd use it to try and convert an IA or IB into a C:

IA^ temp = /* get a C in some way. */;
C^ tempC = dynamic_cast<C^>(temp);
Related Topic