ProgrammingVery hardProduct-company placement · C++

Which line fails to compile?

Which line fails to compile?
struct A { virtual ~A() { } };
struct B { virtual ~B() { } };
struct C : A, B { };
int main() {
    A* a = new C;
    B* b1 = dynamic_cast<B*>(a);   // L1
    B* b2 = static_cast<B*>(a);    // L2
}
  1. A. L1 only
  2. B. L2 only
  3. C. Both
  4. D. Neither

Correct answer: B. L2 only

A and B are unrelated types, so static_cast cannot convert between them. dynamic_cast can 'cross-cast' at run time because the actual object is a C that has both bases; b1 is non-null.

More OOP with C++ and Java questions

Exams that ask this topic