Name hiding vs overriding: if base and derived define a function with the same prototype, which function is called?

Difficulty: Easy

Correct Answer: Base class object will call base class function and derived class object will call derived class function.

Explanation:


Introduction / Context:
When both base and derived classes declare a function with the same signature, the behavior depends on whether the base function is virtual and on the static type of the expression used to call it. Understanding this clarifies how overriding and name hiding interact in typical class hierarchies.


Given Data / Assumptions:

  • Base and derived both define a function with the same prototype.
  • No additional qualifiers are mentioned; assume standard visibility and access.
  • We consider calls through actual objects of base or derived types.


Concept / Approach:

If the function is not virtual, the selection is based on the static type of the expression: a base object calls the base version; a derived object calls the derived version (overload resolution picks the member within the respective class; there is no runtime redirection). If the base declares the function virtual and the call is made through a base reference or pointer to a derived object, dynamic binding will select the derived override at runtime. In either case, a base object never calls the derived version, because it lacks the derived subobject and has its own layout and vtable (if any).


Step-by-Step Solution:

1) Consider a Base b; and Derived d; where Derived : Base and both define f(). 2) Call b.f(); ⇒ invokes Base::f(). 3) Call d.f(); ⇒ invokes Derived::f(). 4) For pointers/references, if virtual, Base* p = &d; p->f(); dispatches to Derived::f().


Verification / Alternative check:

Compile and run a sample with and without the virtual keyword to see the difference between static and dynamic binding. Inspecting assembly or debugger views shows vtable-based indirection in the virtual case only.


Why Other Options Are Wrong:

Error: redefining a member in a derived class is legal; it hides or overrides depending on virtual.

“Only base” or “only derived” irrespective of object: both contradict standard dispatch rules.


Common Pitfalls:

  • Expecting derived to run when calling a non-virtual function through a base object.
  • Confusing object calls with pointer/reference calls where dynamic binding applies.


Final Answer:

Base class object will call base class function and derived class object will call derived class function.

More Questions from OOPS Concepts

Discussion & Comments

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