ProgrammingHardProduct-company placement · C++

What is printed?

What is printed?
struct B { virtual ~B() { } };
struct D : B { };
struct E : B { };
int main() {
    B* p = new D;
    cout << (dynamic_cast<D*>(p) != nullptr) << (dynamic_cast<E*>(p) != nullptr);
    try { E& e = dynamic_cast<E&>(*p); cout << "ok"; }
    catch (std::bad_cast&) { cout << "bad"; }
}
  1. A. 11ok
  2. B. 10bad
  3. C. 10ok
  4. D. 00bad

Correct answer: B. 10bad

dynamic_cast checks the actual object: a D is not an E, so the pointer cast yields nullptr. A failed cast to a REFERENCE cannot return null and throws std::bad_cast instead.

More OOP with C++ and Java questions

Exams that ask this topic