- Asked 2/10
- 2073 Shrawan · 5 marks
- 2068 Chaitra · 2 marks
Access overridden members from derived class
What do you mean by function overriding? How can we access overridden members of the base class from a member function in the derived class? Explain with example.
Function overriding is redefining a member function of the base class in the derived class with the same name, return type and parameter list. When the function is called with a derived class object, the derived version is executed and the base version is hidden.
Accessing the overridden base member: use the scope resolution operator :: with the base class name.
- Inside a derived member function:
Base::display(); - From outside, with a derived object:
d.Base::display();
#include <iostream>
using namespace std;
class Base {
public:
void display() { cout << "Base display" << endl; }
};
class Derived : public Base {
public:
void display() { // overrides Base::display()
cout << "Derived display" << endl;
Base::display(); // call the overridden base version
}
};
int main() {
Derived d;
d.display(); // Derived version, which also calls Base's
d.Base::display(); // directly call the hidden base version
return 0;
}
Output:
Derived display
Base display
Base display
Without Base::, the call display() inside Derived::display() would call itself recursively. The Base:: prefix tells the compiler which class's function to use.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Member function overriding with virtual function · Object Oriented Programming, chapter 7
- Member function as friend of another class · Object Oriented Programming, chapter 4
- Static data member and member function · Object Oriented Programming, chapter 4 · asked 3×
- Function overriding versus overloading · Object Oriented Programming, chapter 6 · asked 2×
- Function overriding and how to resolve it · Object Oriented Programming, chapter 6
- Manager derived from person and employee · Object Oriented Programming, chapter 6
- Sending structure members to a function · Computer Programming, chapter 8
- Structure vs array; accessing members · Computer Programming, chapter 8
- Video rental shop class diagram · Object Oriented Analysis and Design, chapter 2
- Truss joint B: temperature and vertical members long · Theory of Structures I, chapter 3 · asked 2×