Reputation: 2890
I've done some searching for this, but just to make sure:
Using dynamic_cast
to cast a base-class pointer to a derived-class pointer requires the base class to be polymorphic? Otherwise we won't even be able to compile?
Thanks.
Upvotes: 1
Views: 627
Reputation: 60979
For Upcasts, the base class type - which is the type of the casted expression - has to be polymorphic, otherwise you get a compiler error.
That is because dynamic_cast
uses RTTI to perform the cast and check whether it is successful or not - and RTTI is only generated for polymorphic types.
static_cast
on the other hand doesn't check whether the cast is valid; if it isn't, the cast invokes undefined behavior. static_cast
just adds or subtracts an offset from the pointer (or internal pointer of the reference). dynamic_cast
does a runtime type check.
Upvotes: 1
Reputation: 73376
You could use dynamic_cast to cast a derived class to a non polymorphic base class. But you cannot dynamic_cast a non polymorphic base to a derived class.
The standard explains (§5.2.7):
(1) The result of the expression dynamic_cast(v) (...)
(5) If T is “pointer to cv1 B” and v has type “pointer to cv2 D” such that B is a base class of D, the result is a pointer to the unique B subobject of the D object pointed to by v.
(6) Otherwise, v shall be a pointer to or a glvalue of a polymorphic type
The polymorphic is meant here in a very humble sense: "A class that declares or inherits a virtual function is called a polymorphic class." (§10.3/1).
Upvotes: 2