2

Here the second cast gives an error saying

cast.cc:35:35: error: cannot dynamic_cast ‘base’ (of type ‘class CBase*’) to type ‘class CDerived*’ (source type is not polymorphic)

 CBase * base = new CDerived; CBase* pb; CDerived * der = new CDerived; CDerived* pd; pb = dynamic_cast<CBase*>(der); // ok: derived-to-base pd = dynamic_cast<CDerived*>(base); // wrong: base-to-derived 

What is meannt by this ??

And why this works if I make the base class polymorphic ?

Can some one please let me know the basic concept behind this.

1 Answer 1

5

Because the standard says so (see the section [expr.dynamic.cast] in the C++ standard):

... dynamic_cast<T>(v)

... v shall be a pointer to or an lvalue of a polymorphic type

In practice, because the run-time type information (RTTI) required to make dynamic down-casts (i.e. from base to derived) possible are generated along with the vtbl/vptr mechanism, which isn't required if there are no polymorphic member functions.

Up-casts (i.e. derived to base), on the other hand, require no RTTI (there's no run-time decision to be made). Quoting from the same section of the standard:

struct B { }; struct D : B { }; void foo(D* dp) { B* bp = dynamic_cast<B*>(dp); // equivalent to B* bp = dp; } 
Sign up to request clarification or add additional context in comments.

2 Comments

Does the compiler substitute a static_cast for the dynamic_cast when it knows it's a derived-to-base conversion? That's what you're implying, right?
@MarkRansom: I guess that's what I'm implying, but I'm not going to make it explicit, in case it's wrong!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.