ProgrammingHardAccenture · Cognizant pattern
What is printed?
What is printed?
struct Base {
virtual void f() { cout << "Base-f "; g(); }
void g() { cout << "Base-g"; }
};
struct Derived : Base {
void f() override { cout << "Derived-f "; }
void g() { cout << "Derived-g"; }
};
int main() {
Base *p = new Derived;
p->f();
}- A. Derived-f
- B. Base-f Derived-g
- C. Derived-f Base-g
- D. Base-f Base-g
Correct answer: A. Derived-f
f() is virtual, so p->f() dispatches to Derived::f() at runtime, which only prints "Derived-f " and, since Derived::f overrides the whole body (it does not call Base::f), g() is never invoked at all.
More OOP with C++ and Java questions
- What is printed? java class A { static { System.out.print("A-static "); } } class B extends A { static { System.out.print("B-static "); }…
- What is printed? java class Parent { int bonus() { return 10; } } class Child extends Parent { static int bonus(int n) { return n + 1; } }…
- What is printed? java class A { { System.out.print("IB-A "); } A() { System.out.print("CTOR-A "); } } class B extends A { {…
- What is printed? cpp void f(int x) { cout << "int"; } void f(double x) { cout << "double"; } int main() { f('a'); }
- What happens when this is compiled? java class A { final void m() { System.out.println("A"); } } class B extends A { void m() {…
- What happens when this is compiled? java class Picker { static void f(String s) { System.out.print("String"); } static void…