Difficulty: Easy
Correct Answer: Correct — a call on a derived-class object resolves to the derived member even without virtual.
Explanation:
Introduction / Context:
The prompt evaluates function resolution when a base class and a derived class both declare a function with the same name. This is a core concept in C++ related to name lookup, overload resolution, and (optionally) dynamic dispatch when virtual functions are involved.
Given Data / Assumptions:
Concept / Approach:
In C++, unqualified member calls follow class member name lookup that starts at the most derived class of the expression’s static type. If the derived class declares a member with the same name, it hides the base member of the same name. Therefore, when you call the function on a derived object, the derived version is selected regardless of whether the function is declared virtual. Virtual only matters when the call occurs through a base pointer or reference and you want runtime polymorphism; for direct calls on a derived object, the derived declaration wins at compile time.
Step-by-Step Solution:
Verification / Alternative check:
If you explicitly want the base version, you must qualify the call: d.Base::f(...); or remove/hide the derived overload. Through a Base* or Base& expression, dynamic dispatch requires virtual
for runtime selection.
Why Other Options Are Wrong:
Common Pitfalls:
Confusing direct calls on derived objects with calls via base pointers/references; also forgetting that a new overload in the derived class can hide all base overloads of the same name unless brought in with using Base::f;
.
Final Answer:
Correct — a call on a derived-class object resolves to the derived member even without virtual.
Discussion & Comments