C++ Function Overriding 

Function overriding is achieved when a derived class provides the specific implementation of a member function already defined in its base class.

In this scenario, the member function in the base class is called the overridden function and the member function in the derived class is called the overriding function. There must be an IS-A relationship (i.e. inheritance).

The new function definition in the derived class must have the same function name and same parameter list as in the base class.

Function overriding is an example of runtime polymorphism.

 

Function Overriding Example

Below is an example demonstrating function overriding concept with respect to base class and derived class.

function_override.cpp

// function overriding example
#include <iostream>
using namespace std;

// Base class
class Base {

public:
// base member function (overridden function)
void print() {
cout << "function of base class" << endl;
}
};

// Derived class
class Derived : public Base {

public:
// derived member function (overriding function)
void print() {
cout << "function of derived class" << endl;
}
};

int main() {
// Reference of Derived class points to object of Derived class
Derived ob = Derived(); // (1)

ob.print(); // calling overriding function

// Reference of Base class points to object of Derived class
Base obj = Derived(); // (2)

obj.print(); // calling overridden function

return 0;
}

Output:

function of derived class
function of base class

 

Explanation of the program:

As we have seen in (1) that when we make a call to the member function involved in overriding, the derived class function (overriding function) gets called. 

However, we can call the base class function (overridden function) as shown in (2) by using the object of derived class in such a way that the reference of base class points to it.