ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
struct Base { virtual ~Base() {} };
struct Derived : Base {};
struct Other : Base {};
int main() {
    Base *b = new Derived();
    Other *o = dynamic_cast<Other*>(b);
    cout << (o == nullptr);
}
  1. A. 0
  2. B. 1
  3. C. Compile-time error: dynamic_cast requires a polymorphic source, but Base has none here
  4. D. Undefined behaviour

Correct answer: B. 1

Base has a virtual destructor, so it is polymorphic and dynamic_cast can check the real type at runtime. b actually points at a Derived, which is unrelated to Other, so the downcast fails safely and dynamic_cast returns a null pointer, making o == nullptr true (prints 1).

More OOP with C++ and Java questions

Exams that ask this topic