Table of contents
1.
Introduction
2.
What is C++ Override?
3.
How Override Works?
4.
Use cases of the override Keyword
4.1.
Enhancing the readability of code
4.2.
Accidental mismatches prevention
4.3.
Catching errors during compilation
4.4.
Consistently enforcing an inheritance hierarchy
4.5.
Improving the maintainability of code
4.6.
Enhanced code reusability
4.7.
Improved documentation
4.8.
Improved performance
5.
Examples of override keyword Use
6.
Examples of override keyword Use
6.1.
Example 1 - Using override keyword to catch errors during compile time.
6.2.
Example 2 - Enforcing a consistent inheritance hierarchy using the override keyword
6.3.
Example 3 - The override keyword is used to improve code performance, readability, and maintainability.
7.
Advantages of Using Override
8.
Disadvantages of Using Override
9.
Best Practices for Using Override
10.
Limitations and Caveats 
11.
Frequently Asked Questions
11.1.
Why do we use @override?
11.2.
When should I use override C++?
11.3.
Is override a reserved keyword in C++?
11.4.
What are the local class and global class?
12.
Conclusion
Last Updated: Dec 23, 2024
Easy

Override Keyword in C++

Author Prashansa
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In C++ programming, the 'override' keyword plays a crucial role in ensuring the correctness and maintainability of code. Understanding its nuances is essential for writing robust and error-free programs. 

Before diving deeper, make sure you understand classes ,object and functions in C++.

C++ override

What is C++ Override?

The "override" keyword in C++ serves as a clear indication to the compiler that a virtual function in a derived class is meant to replace a virtual function with the same name in the base class. By using "override," you ensure that the function signature in the derived class matches exactly with the one in the base class, strengthening the code's correctness and making it more maintainable.

How Override Works?

Override keyword/identifier is placed after the declaration of a member function in the derived class, and it works to check during compilation if we have a virtual function with the same name and same parameters in the base class or not, If the virtual function with same specifications doesn’t exist it throws a compile time error.

Use cases of the override Keyword

The override keyword can be useful for a variety of purposes, such as:

Enhancing the readability of code

Explicitly marking overridden functions with the 'override' keyword improves code readability and understanding by clearly indicating the intended purpose of the function.

Accidental mismatches prevention

The 'override' keyword helps prevent accidental mismatches between base class and derived class functions, reducing the risk of unintended behavior or errors.

Catching errors during compilation

Using 'override' enables the compiler to catch errors at compile-time, such as misspelled function names or incorrect parameter types, enhancing code reliability.

Consistently enforcing an inheritance hierarchy

By using 'override', developers can ensure that derived classes correctly override virtual functions defined in base classes, maintaining a consistent and predictable inheritance hierarchy.

Improving the maintainability of code

Clear indication of overridden functions with 'override' aids in code maintenance and updates, as developers can easily identify overridden functions and their relationships within the inheritance hierarchy.

Enhanced code reusability

'override' promotes code reusability by clearly delineating the relationship between base and derived classes, facilitating the reuse of base class implementations in derived classes.

Improved documentation

Explicitly marking overridden functions with 'override' serves as documentation, conveying the intended behavior of derived class functions and their relationship to base class functions.

Improved performance

While not a direct performance enhancement, using 'override' can indirectly contribute to improved performance by reducing the likelihood of runtime errors and facilitating compiler optimizations through clearer code semantics.

Examples of override keyword Use

Examples of override keyword Use

Here is an example demonstrating the use of the override keyword in C++ to catch errors during compile time.

Example 1 - Using override keyword to catch errors during compile time.

#include <iostream>

class Base {
public:
    virtual void print() const {
        std::cout << "Base::print()" << std::endl;
    }
};

class Derived : public Base {
public:
    // Error: The function signature does not match the base class function
    void print(int x) const override {
        std::cout << "Derived::print()" << std::endl;
    }
};

int main() {
    Derived d;
    d.print();
    return 0;
}

Explanation: In this example, we have a base class Base with a virtual function print(). The derived class Derived attempts to override the print() function but provides a different function signature (with an additional parameter). This results in a compilation error due to the use of the override keyword, indicating a mismatch between the derived class function and the base class function signature.

Example 2 - Enforcing a consistent inheritance hierarchy using the override keyword

#include <iostream>

class Base {
public:
    virtual void print() const {
        std::cout << "Base::print()" << std::endl;
    }
};

class Derived : public Base {
public:
    void print() const override {
        std::cout << "Derived::print()" << std::endl;
    }
};

int main() {
    Derived d;
    d.print();
    return 0;
}

Explanation: In this example, the derived class Derived correctly overrides the print() function from the base class Base. By using the override keyword, we enforce a consistent inheritance hierarchy, ensuring that the derived class function matches the base class function signature. This enhances code maintainability and readability, as well as catching errors during compilation if the function signatures do not match.

Example 3 - The override keyword is used to improve code performance, readability, and maintainability.

#include <iostream>

class Shape {
public:
    virtual double area() const = 0;
};

class Rectangle : public Shape {
private:
    double width, height;
public:
    Rectangle(double w, double h) : width(w), height(h) {}

    double area() const override {
        return width * height;
    }
};

int main() {
    Rectangle rect(5.0, 3.0);
    std::cout << "Area of rectangle: " << rect.area() << std::endl;
    return 0;
}

Explanation: In this example, the override keyword is used to indicate that the area() function in the Rectangle class overrides the virtual function area() in the base class Shape. This improves code performance by allowing the compiler to optimize function calls and improves code readability and maintainability by explicitly indicating the function's intent and relationship with the base class. Additionally, using override ensures that any changes to the base class function signature are reflected in the derived class, reducing the risk of errors during code maintenance.

Advantages of Using Override

  • Compile time checking - By using the override keyword, the compiler can catch errors at compile time if a function in derived class overrides the implementation of a virtual function of the base class or not.It helps the programmer to write bug free code and identify errors at compile time instead of run time.
     
  • Maintainability-  If the virtual function of the base class changes in future, this identifier can help us make changes to all the derived classes which override this function and make changes hence helping in the maintenance of a big code base.
     
  • Readability-  Multiple programmers working on the same code base will find the code to be more clear and understandable if we have such identifiers in our code which indicates if a function overrides a virtual function or not.

Disadvantages of Using Override

  • Confusion and Errors- If the overridden method is changed in the base class, the overridden method in the derived class may not work as expected. For example, if the base class method throws an exception, the derived class method may not be able to catch it
     
  • Reduced Maintainability- If there are many overridden methods, it can be difficult to keep track of which methods are overridden and how they are implemented. This makes code difficult to understand and maintain
     
  • Reduced Performance- Overriding methods can lead to additional method calls, which can reduce performance. This is because the overridden method in the derived class must first call the base class method and then execute its own code
     
  • Less Flexibility- If a method is overridden, it can not easily be reused in other classes. This is because the overridden method in the derived class is specific to the derived class

Best Practices for Using Override

  • Always use override when you are overriding a function it helps in improving the readability of code and prevents bugs to occur at runtime as it will report issues with overriding at compile time itself.
     
  • Make sure to use override only with virtual functions, they are not meaningful in the case of static member functions and non-virtual functions.
     
  • Always make sure to have the same signature and constness as the derived class function it should exactly match with the base class virtual function, including the return type, parameter types and constness

Limitations and Caveats 

  • It is only useful for virtual functions and doesn't work with non-virtual functions and will throw a compile time error if used with them.
     
  • It enables only compile-time checks for checking the flow if the function overrides the base class implementation or not, but it doesn’t have any runtime checks.
     
  • It is limited to checking the correctness of the function signature of the derived class function with base class function for overriding but doesn’t catch any other errors like undefined behaviour or null pointer dereferences etc.

Frequently Asked Questions

Why do we use @override?

We use override in C++ to explicitly indicate that a function in a derived class overrides a virtual function in the base class.

When should I use override C++?

override should be used in C++ whenever a derived class function is intended to override a virtual function in the base class.

Is override a reserved keyword in C++?

No override is not a reserved keyword in C++. It is an identifier, with a special meaning. When used after a function, an override identifier ensures that the function is virtual and overrides a virtual function from a base class.

What are the local class and global class?

Global classes are defined inside the main function and not in any particular function, so all the functions in the code can access them. In comparison, local classes are declared inside a specific function and are local to that function itself.

Conclusion

In this article, we learnt that the C++ override Keyword is very useful to ensure that virtual functions in the derived class override correct the virtual functions in the base class; it can help catch errors at compile time, improves code maintainability and readability, and identify bugs at early stages of development.
However, please keep in mind that it has its own limitations that it only works with virtual functions and provides only compile time checks and doesn’t check for such failures at run time.

Hope this article helped you in your learning process.

Suggested reading

Live masterclass