ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
struct A { virtual void f() { cout << "A"; } };
struct B : A { void f() override { cout << "B"; } };
struct C : B { void f() override { cout << "C"; } };
int main() {
A a; B b; C c;
A *arr[3] = { &a, &b, &c };
for (auto *p : arr) p->f();
}- A. AAA
- B. ABC
- C. CCC
- D. Compile-time error: cannot mix A, B, C objects in an A* array
Correct answer: B. ABC
A*[3] can hold pointers to A or any derived type; each pointer's real pointee determines the virtual dispatch, independent of the other elements. &a is a plain A, printing A; &b is a B, printing B (its own override); &c is a C, printing C. Result: ABC.
More OOP with C++ and Java questions
- Does this compile? java public class Main { public static void main(String[] args) { try { throw new RuntimeException("x"); } catch…
- What is printed? java public class Main { public static void main(String[] args) { try { Object[] arr = new String[3]; arr[0] = 100; }…
- What is printed? cpp void f() { try { throw 10; } catch (double d) { cout << "double:" << d; } catch (int i) { cout << "int:" << i; } }…
- What is printed? java public class Main { public static void main(String[] args) { int[] arr = {1, 2, 3}; try {…
- What is printed? java class Base { final void secure() { System.out.print("Base.secure"); } } class Derived extends Base { // void…
- What is printed? cpp class Base { public: virtual void f() final { cout << "Base::f "; } }; class Derived : public Base { public: // void…