- 2074 Chaitra · 4 marks
Function overriding and how to resolve it
Short answer
Function overriding is redefining a base function with identical signature in a derived class. Resolution is static (based on pointer/reference type) for non-virtual functions; dynamic via virtual functions where the actual object type decides at runtime; the overridden base version can be explicitly called with Base::function.
What is function overriding? How can it be resolved? Explain with a suitable example.
Function overriding means a derived class defines a function with the same name, return type and parameters as a function of its base class. The derived version hides the base version for derived objects. The question of "resolving" is deciding which version is called.
Resolution:
- Static (compile-time) resolution - the version is chosen by the type of the object or pointer. A derived object calls the derived function; a base pointer calls the base function.
- Scope resolution operator - the hidden base version can be called explicitly as
Base::fun(). - Virtual functions (dynamic resolution) - if the base function is
virtual, the version is chosen at run time by the actual object type, even through a base pointer.
Example:
#include <iostream>
using namespace std;
class Base {
public:
void show() { cout << "Base::show" << endl; }
virtual void print() { cout << "Base::print" << endl; }
};
class Derived : public Base {
public:
void show() { cout << "Derived::show" << endl; }
void print() { cout << "Derived::print" << endl; }
};
int main() {
Derived d;
Base *p = &d;
d.show(); // Derived::show (derived object)
d.Base::show(); // Base::show (scope resolution)
p->show(); // Base::show (non-virtual: pointer type decides)
p->print(); // Derived::print (virtual: object type decides)
return 0;
}
Output:
Derived::show
Base::show
Base::show
Derived::print
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Function overriding versus overloading · Object Oriented Programming, chapter 6 · asked 2×
- Member function overriding with virtual function · Object Oriented Programming, chapter 7
- Ambiguity and how to resolve it · Object Oriented Programming, chapter 6