C++ Function Overriding is a feature in C++ that allows a derived class to provide a new implementation for a virtual function that is already provided by the base class. The new implementation provided by the derived class is said to override the implementation provided by the base class.
To understand function overriding, let's consider the following C++ example program.
#include <iostream> using namespace std; class Shape { public: void calculateArea() { cout << "Calculating area of Shape" << endl; } }; class Rectangle : public Shape { public: void calculateArea() { cout << "Calculating area of Rectangle" << endl; } }; int main() { Shape shape; shape.calculateArea(); Rectangle rectangle; rectangle.calculateArea(); return 0; }Output
Calculating area of Shape Calculating area of Rectangle
In this example, we have a Shape class with a calculateArea method that simply outputs a message. We also have a Rectangle class that derives from the Shape class. The Rectangle class provides its own implementation for the calculateArea method.
As we can see from the output, the implementation of the calculateArea method in the Rectangle class overrides the implementation in the Shape class. When we create a Shape object, its calculateArea method is called, and the output is "Calculating area of Shape". When we create a Rectangle object, its calculateArea method is called, and the output is "Calculating area of Rectangle".
In this way, C++ Function Overriding allows us to provide new implementations for Overridden functions in derived classes, allowing for better code reusability and more efficient use of inheritance.