Search code examples
c++polymorphismdynamic-cast

why does dynamic_cast return null with multiple level inheritance


While reviewing an inherited project which is to port from an old version of Visual Studio (6) to a new version (2017), we stumbled across this run time error, in that we were getting an unexpected NULL after using dynamic_cast<>() on a base class. Here is a representative sample:

Given this code:

class a { public: a() {}; virtual ~a() {}; };

class b :public a { public: b() {};  virtual ~b() {}; };

class c : public b { public: c() {};  virtual ~c() {}; };

int main()
{
    a *a_ = new b();
    b *b_ = new c();
    c *c_1 = dynamic_cast<c*>(b_); //<-- returns c_1 = non-null(actual pointer value)
    c *c_2 = dynamic_cast<c*>(a_); //<-- returns c_2 = NULL
}

I believe the author has all the classes set up properly for dynamic_cast<>(). Class c 'is a' Class a so that seems satisfied, and Class c 'is a' Class b so that seems satisfied.

I'm wondering if the problem lies in the fact that a_ is actually a derived Class b, which could theoretically be in fact a derived pointer to a hypothetical Class d. I'm rusty on my c++ and I could use some help here as to the root cause and a proper solution.


Solution

  • a_ points to a b. When you attempt dynamic_cast<c*>(a_); to try to get a c out of it there is no c object, only a b so the cast fails and you get a null pointer. b_ works becuase b_ actually points to a c.