Junior
What is overriding (override) in C++?
sobes.tech AI
Answer from AI
Override is a mechanism in object-oriented programming where a derived class provides its specific implementation of a virtual function declared in the base class. When such a function is called through a pointer or reference to the base class, the implementation from the actual type of the object (derived or base) will be executed, depending on whether the function was overridden.
Main points:
- It applies only to virtual functions.
- The signature (name, return type, parameter types and count) of the overriding function in the derived class must exactly match the signature of the overridden function in the base class.
- The keyword
override(starting from C++11) is used to explicitly indicate the intention to override a function. The compiler will check whether the function from the base class exists with such a signature and will produce an error if not. This helps avoid typos and makes the code more readable.
Example:
class Base {
public:
virtual void print() {
// Base class implementation
// ...
}
virtual void display(int x) const {
// Another virtual function
// ...
}
};
class Derived : public Base {
public:
// Override the print function from Base
void print() override {
// Specific implementation for Derived
// ...
}
// This is not an override because it lacks const
/*
void display(int x) {
// Compilation error with override keyword
// ...
}
*/
// Correct override of the display function from Base
void display(int x) const override {
// Specific implementation for Derived
// ...
}
};