How to call an overridden function in C++

A function can be overridden using inheritance to change its behavior. However, sometimes, we don’t need to completely alter or replace the functionality of the base (parent) class; instead, we need to add more functionality. In order to do this, the derived (child) class can call the parent’s function first (using the scope resolution operator ::) and then implement the additional functionality.

Re-using the parent’s code lets us write less code in the derived class.

svg viewer

Code

#include <iostream>
using namespace std;
class Base{
public:
void foo(){
cout << "Base class functionality" << endl;
}
};
class Derived: public Base{
public:
// Overriding foo():
void foo(){
Base::foo(); // Calling foo() of Base class
cout << "Derived class functionality" << endl;
}
};
int main() {
Derived d;
d.foo();
return 0;
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved