ProgrammingVery hardIBM · Deloitte pattern
What is printed?
What is printed?
struct Base {
virtual void f() const { cout << "Base "; }
};
struct Derived : Base {
void f() const override { cout << "Derived "; }
void f(int x) { cout << "Derived-int "; }
};
int main() {
Base *p = new Derived;
p->f();
}- A. Derived
- B. Base
- C. Derived-int
- D. Compilation error: ambiguous overload between f() and f(int)
Correct answer: A. Derived
Overload resolution for p->f() only considers signatures visible through the static type Base (just f() const), so there's no ambiguity with Derived's extra f(int); among that single candidate, virtual dispatch then picks the actual override, Derived::f() const, printing "Derived".
More OOP with C++ and Java questions
- What is printed? cpp struct Base { virtual Base clone() const { cout << "Base::clone "; return new Base(this); } }; struct Derived : Base…
- What is printed? java interface Greeter { String greet(); } class Main { public static void main(String[] args) { Greeter g = () -> "hi…
- What is printed? cpp struct Resource { virtual ~Resource() { cout << "~Resource "; } }; struct FileResource : Resource { ~FileResource() {…
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : virtual A { void f() override { cout << "B"; } }; struct C…
- What is printed? java class Node { Node next; int val; Node(int v) { val = v; } public String toString() { return val + (next != null ?…
- What is printed? java class A { final String tag() { return "A"; } } class B extends A { String tag(int x) { return "B" + x; } } // in…