Function Overriding in C++
Introduction to Function Overriding
Function overriding is a feature of object-oriented programming languages like C++ that allows a derived class to provide a specific implementation of a function that is already defined in its base class. The overridden function in the derived class should have the same signature (name, return type, and parameters) as the one in the base class.
Why Use Function Overriding?
Function overriding is used to achieve runtime polymorphism. It allows you to invoke derived class methods through base class pointers or references, enabling you to write more flexible and reusable code. It's particularly useful when you want to ensure that a particular method is executed based on the actual object type rather than the reference type.
Syntax of Function Overriding
To override a function, the derived class function must have the same name, return type, and parameter list as the base class function. Here's the basic syntax:
class BaseClass { public: virtual void display() { // Base class implementation } }; class DerivedClass : public BaseClass { public: void display() override { // Derived class implementation } };
The virtual
keyword in the base class function declaration ensures that the function can be overridden. The override
keyword in the derived class function declaration is optional but recommended for clarity.
Example of Function Overriding
Let's look at a complete example to understand how function overriding works in C++.
#include <iostream> using namespace std; class Base { public: virtual void show() { cout << "Base class show function" << endl; } }; class Derived : public Base { public: void show() override { cout << "Derived class show function" << endl; } }; int main() { Base* basePtr; Derived derivedObj; basePtr = &derivedObj; // This will call the overridden function in the derived class basePtr->show(); return 0; }
In this example, the show
function in the Derived
class overrides the show
function in the Base
class. When the show
function is called through the base class pointer, the derived class implementation is executed.
Output
Rules of Function Overriding
While overriding a function, you should follow these rules:
- The function must have the same signature in both the base and derived classes.
- The base class function must be declared with the
virtual
keyword. - The access level (public, protected, or private) of the overridden function can be different from that of the base class function.
- Use the
override
keyword in the derived class function for better readability and error checking.
Conclusion
Function overriding is a powerful feature in C++ that enables runtime polymorphism and allows derived classes to provide specific implementations for functions defined in base classes. Understanding and using function overriding effectively can help you write more flexible and maintainable code.