ProgrammingVery hardProduct-company placement · C++

What is printed?

What is printed?
struct B { virtual void f() { cout << "B"; } };
struct D : B { void f() override { cout << "D"; } };
int main() {
    void (B::*pf)() = &B::f;
    D d;
    (d.*pf)();
}
  1. A. B
  2. B. Compile-time error: cannot apply a B member pointer to a D
  3. C. D
  4. D. BD

Correct answer: C. D

A pointer to a VIRTUAL member function still dispatches virtually when called, so through a D object it invokes D::f even though it was formed from &B::f.

More OOP with C++ and Java questions

Exams that ask this topic