ProgrammingHardIBM · Deloitte pattern
What is printed?
What is printed?
struct A {
virtual std::string name() const { return "A"; }
};
struct B : A {
std::string name() const override { return "B(" + A::name() + ")"; }
};
struct C : B {
std::string name() const override { return "C(" + B::name() + ")"; }
};
int main() {
A *p = new C();
cout << p->name();
}- A. C(B(A))
- B. A
- C. C(A)
- D. B(A)
Correct answer: A. C(B(A))
p->name() dispatches virtually to the most-derived override, C::name, which explicitly calls B::name() (a statically bound call), which itself explicitly calls A::name() (returning "A"). Building up the string: B wraps it as B(A), and C wraps that as C(B(A)).
More OOP with C++ and Java questions
- What is printed? cpp struct Member { Member() { std::cout << "Member "; } ~Member() { std::cout << "~Member "; } }; struct Base { Base() {…
- What is printed? cpp struct A { A() { std::cout << "A "; } }; struct B { B() { std::cout << "B "; } }; struct C : A, B { C() { std::cout…
- What is printed? java class A { A() { System.out.print("A "); init(); } void init() { System.out.print("A.init "); } } class B extends A {…
- What is printed? java public int test() { try { return 1; } finally { System.out.println("finally"); } } // caller…
- What is printed? java public int test() { try { return 1; } finally { return 2; } } // caller prints test()
- What is printed? java class MyChecked extends Exception {} class Test { static void risky() throws MyChecked { throw new MyChecked(); }…