What does dynamic_cast<Derived*>(basePtr) return when the object is not actually a Derived?
Correct answer
D. nullptr for a pointer cast, while the reference form throws std::bad_cast
15 views
D. nullptr for a pointer cast, while the reference form throws std::bad_cast
15 views
dynamic_cast performs a run-time checked conversion using RTTI and needs a polymorphic source type, meaning at least one virtual function. Pointer failure is reported as nullptr so it can be tested, while reference failure throws std::bad_cast because a reference cannot be null. static_cast performs no check and is cheaper when the type is already known.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is D? Ask here and get an explanation.