Question

Say I have two classes

class foo
{
   .......
   virtual ~foo() {..}
};

class foobar : public foo
{
};

The following does not cause an error:

foo* c = new foo();
foobar* j = dynamic_cast<foobar*>(c);

However the following cast causes an error at runtime:

foo c;
foo &d = c;
foobar& j = dynamic_cast<foobar&>(d);

Why does casting work with pointers but not with references?

Was it helpful?

Solution

The cast fails in both cases, as expected.

In the first case, it returns a nullptr, which you should test against before de-referencing the pointer. In the second case, there isn't anything that can be returned, and the cast raises an std::bad_cast exception. This what dynamic_castis designed to do.

OTHER TIPS

You can use dynamic_cast when the pointer/reference is actually pointing to an object of a derrived class. But in your case the object is actually of class foo, not foobar. So first one will give nullptr and second one will raise exception.

 foo* ob = new foobar();
 foobar* f_ob = dynamic_cast<foobar*>(ob);

similar for reference.

There is no null reference. dynamic_cast cannot return a nullptr to indicate that the dynamic type of this object is not compatible with target type, so it raises a std::bad_cast.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top