C++ inheritance lookup: when a child (derived) class function is called on an object, where does the compiler look first for a matching function signature/name?
Computer Science
Object Oriented Programming Using C++
Difficulty: Easy
Choose an option
-
Aclass of the object using the function name
-
Bimmediate ancestor class
-
Cbase class
-
Ddescendant class
-
ENone of the above
Answer
Correct Answer: class of the object using the function name
Explanation
Introduction / Context:Name lookup and overload resolution in C++ proceed from the most specific scope outward. When invoking a member function on an object, the compiler tries to bind the call by first considering members of the object’s own (most-derived) class, then searching base classes as needed. This ordering affects which overload is chosen or whether a base member is hidden.
Given Data / Assumptions:
- Single or multiple inheritance may be present.
- Virtual dispatch is a runtime concept; name lookup and overload resolution occur at compile time.
- The question asks about the starting point of lookup, not virtual override binding.
Concept / Approach:
- Unqualified member lookup begins in the class of the object expression.
- If not found, lookup proceeds to immediate base classes, then further bases.
- Derived-class declarations can hide base-class members of the same name.
Step-by-Step Solution:
Given obj.f(), search starts in type(obj).If no match, move to direct base(s), then ascend the hierarchy.Therefore, the first search location is the class of the object using the function name.Verification / Alternative check:
Test with a derived class redefining f(): the derived definition is chosen; removing it exposes the base version—confirming lookup order.Why Other Options Are Wrong:
- Immediate ancestor/base class: Searched only if not found in the object’s class.
- Descendant class: More derived than the current type does not exist for that object.
- None of the above: Incorrect because option A is precise.
Common Pitfalls:
- Confusing compile-time lookup with runtime virtual dispatch (which chooses the most-derived override at runtime).
- Forgetting that derived declarations can hide base overloads unless using-declarations are introduced.
Final Answer:
class of the object using the function name