What is the mechanism of method overriding (override) in C++?
sobes.tech AI
Answer from AI
The method overriding mechanism in C++ allows a derived class to provide its own implementation of a method that is already declared in its parent class. This is a key element of runtime polymorphism.
For successful overriding, the following conditions must be met:
- The method in the base class must be declared as virtual.
- The method name in the derived class must match the method name in the base class.
- The argument list of the methods must be identical (including constness).
- The return type must be either the same or covariant (for pointers or references).
- Qualifiers (e.g., const, volatile) must match.
- Both functions must belong to the same class hierarchy (base and derived).
- The accessibility of the method (public, protected, private) can be changed, but usually remains the same or more accessible.
The keyword override (available since C++11) is not mandatory for overriding, but its use is highly recommended as it forces the compiler to check whether the method in the derived class actually overrides a virtual method in the base class. This helps to identify errors such as typos in the method name or signature mismatch.
Example:
#include <iostream>
class Base {
public:
virtual void display() { // Virtual method
std::cout << "Base class display" << std::endl;
}
};
class Derived : public Base {
public:
void display() override { // Overriding method using override
std::cout << "Derived class display" << std::endl;
}
};
int main() {
Base* basePtr = new Derived();
basePtr->display(); // Calls the version from Derived thanks to polymorphism
delete basePtr;
return 0;
}
In this example, when display() is called through a pointer to the base class pointing to a derived class object, the overridden version from the Derived class is invoked.