Junior
Mis on override C++-s?
sobes.tech AI
Vastus AI-lt
Overriding (override) – see 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 object type (derived or base) will be executed, depending on whether the function was overridden.
Main points:
- 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 if 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 const is missing
/*
void display(int x) {
// Compilation error with override
// ...
}
*/
// Correct override of the display function from Base
void display(int x) const override {
// Specific implementation for Derived
// ...
}
};