ProgrammingHardMicrosoft/Google SDE MCQ · GATE CS

What is printed?

What is printed?
struct B { virtual ~B() { } };
struct D1 : B { };
struct D2 : B { };
int main() {
    B* p = new D1;
    cout << (dynamic_cast<D2*>(p) == nullptr);
    try { D2& r = dynamic_cast<D2&>(*p); cout << "ok"; }
    catch (const bad_cast&) { cout << "bad"; }
    delete p;
}
  1. A. 0ok
  2. B. 1ok
  3. C. 0bad
  4. D. 1bad

Correct answer: D. 1bad

A failed dynamic_cast to a pointer type returns nullptr, so the comparison prints 1. A reference cannot be null, so a failed dynamic_cast to a reference type throws std::bad_cast instead.

More OOP with C++ and Java questions

Exams that ask this topic