Skip to main content

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)

All Object Oriented Programming chapter 6 questions →