Question

Quoting from item 45 in C++ Gotchas:

First a dynamic_cast is not necessarily dynamic, in that it may not perform a runtime check. When performing a dynamic_cast from a derived class pointer (or reference) to one of its public base classes no runtime check is needed, because the compiler can determine statically that the cast will succeed. Of course, no cast of any kind is needed in this case, since conversion from a derived class to its public base classes is predefined.

I thought the above description is where a dynamic_cast is normally used (and therefore would do run-time checks??).

Could someone please explain the difference between the above quote and the "typical" need to use a dynamic_cast? This got me confused as to when I need to use dynamic_cast and why I don't need to use it for the above scenario.

Was it helpful?

Solution

class Base {
public:
    virtual ~Base() {}
    // ...
};

class Derived : public Base {
    // ...
};

"Typical use":

void foo(Derived*);

void f(Base* pb)
{
    if (Derived* pd = dynamic_cast<Derived*>(pb)) {
        foo(pd);
    }
}

"Above quote":

void bar(Base*);

void f(Derived* pd)
{
    Base* pb = dynamic_cast<Base*>(pd); // the dynamic_cast is useless here
                                        //  because a Derived IS-A Base, always
    bar(pb); // Note: could as well call directly bar(pd); (implicit conversion)
}

OTHER TIPS

dynamic_cast is mostly used for downcast and cross-cast. The gotcha mentions upcast.

Having structs B1, B2, D:B1, B2:

  • upcast: D* -> B1*, D* -> B2*
  • downcast: D* <- B1*, D* <- B2*
  • cross-cast: B1* <-> B2* (will work if your most derived class is D).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top