开发者

Do I need to use dynamic_cast when calling a function that accepts the base class?

开发者 https://www.devze.com 2022-12-09 20:03 出处:网络
I have some classes like this: interface class IA { }; interface class IB { }; public ref class C : public IA, public IB

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 necessar开发者_StackOverflowy.

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


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);


Since we know bob is of type C^, we know at compile time it can be downcasted to IA^ safely, and so dynamic_cast is equivalent to static_cast here. Moreover, the implicit cast you propose is also safe.

dynamic_cast is only needed when upcasting from a base type to a derived.


No, I would think that in C++/CLI you also don't need the dynamic cast here. Derived* implicitly converts to Base* unless there's an ambiguity w.r.t. multiple inheritance. The same it probably true for "gc-pointers". In C++ a dynamic cast -- when upcasting -- requires polymorphic classes (with at least one virtual function). I don't know how C++/CLI handles it, though. I would think every CLI class is by default polymorphic.

You may want to remove the C++ tag, by the way. ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消