In C++ object-oriented programming, if both a base class and a derived class define a member function with the same name and compatible signature, then calls made on a derived-class object will resolve to the derived version. Is this statement accurate? Provide the most precise judgment.

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:

  • A base class defines a member function f(...).
  • A derived class also defines a member function named f with a compatible signature.
  • The call is performed on a derived-class object, e.g., Derived d; d.f(...);
  • No unusual qualifiers or explicit scope resolution are used at the call site.


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:

Consider Base::f and Derived::f declared with the same signature. Create Derived d; then call d.f(...). Name lookup finds Derived::f first; Base::f is hidden. Therefore the derived version executes.


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:

  • Resolves to base unless virtual: wrong for calls on a derived object; virtual affects base-interface calls.
  • Needs a using-declaration: not required for calling the derived version.
  • Name hiding prevents any call: incorrect; it only hides the base name, not the derived one.


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.

More Questions from Inheritance

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion