What is Override Keyword in C++?

What is Override Keyword in C++?

5 mins read2.6K Views Comment
Updated on Sep 18, 2023 17:50 IST

The override keyword in C++ explicitly specifies that a virtual function in a derived class is intended to replace (or “override”) a virtual function in the base class with the same name.

2023_02_MicrosoftTeams-image-278.jpg

Using the override keyword in C++ helps prevent accidental mismatches between a derived class function and its intended base class virtual function.

Here are the topics that we will cover in this article:

The override keyword also clarifies the intent of the code.

Here is an example of using the override keyword:


 
#include <iostream>
class Base {
public:
virtual void foo() {
std::cout << "Base::foo\n";
}
};
class Derived : public Base {
public:
void foo() override {
std::cout << "Derived::foo\n";
}
};
int main() {
Derived d;
d.foo(); // Output: Derived::foo
return 0;
}
Copy code

Output

Derived::foo

In the example above, the Derived class overrides the foo function in the Base class by specifying override in the function declaration. This ensures that the correct virtual function is called when a Derived object is used in a context where a Base object is expected.

You can also explore SetPrecision in C++ With Examples

Use cases of the override Keyword

The override keyword in C++ is useful in several situations:

Improving code readability

Using the override keyword makes the code more explicit and easier to understand, especially for others who may be reading or working on the code in the future.

Preventing accidental mismatches

The override keyword ensures that a virtual function in a derived class correctly overrides a virtual function in the base class. Without override, a derived class function with the same name as a base class virtual function would hide the base class function and not override it, which can lead to unexpected behavior.

Catching errors at compile-time

If a derived class function is not correctly overriding a virtual function in the base class, the use of the override keyword will result in a compile-time error, making it easier to find and fix the problem.

Enforcing a consistent inheritance hierarchy

The use of the override keyword helps to enforce a consistent inheritance hierarchy, as it requires that a derived class function have the same signature as the base class virtual function, it is intended to override.

Enhancing code maintainability

The override keyword makes it easier to maintain code, as it helps to prevent unintended changes to the inheritance hierarchy that can occur as code is modified over time.

Improved code reuse

By explicitly specifying the relationship between virtual functions in the base and derived classes, the override keyword makes it easier to reuse code and build upon existing classes consistently and maintainable.

Better documentation

The override keyword can serve as documentation, indicating the intended behaviour of virtual functions in the inheritance hierarchy.

Improved performance

In some cases, using the override keyword can improve performance, allowing the compiler to generate more optimized code by taking advantage of the knowledge of the inheritance hierarchy.

Overall, using the override keyword in C++ can lead to clearer, more maintainable, and more reliable code and is a recommended practice when writing virtual functions in derived classes.

You can also explore: What are Getline Function in C++?

Recommended online courses

Best-suited C++ courses for you

Learn C++ with these high-rated online courses

– / –
4 months
4.24 K
6 weeks
– / –
15 days
– / –
– / –
7.14 K
5 weeks
name
SoloLearnCertificateStar Icon4.5
Free
– / –
– / –
4 months
– / –
3 months

Drawbacks of using the override keyword

There are some potential drawbacks to using the override keyword in C++:

  1. Increased compile time: Using the override keyword may increase the time required to compile the code, as the compiler needs to perform additional checks to ensure that the virtual function in the derived class correctly overrides the virtual function in the base class.
  2. Compatibility with older compilers: The override keyword was introduced in C++11 and is not supported in older compilers. If your code needs to be compatible with older compilers, you may need to avoid using the override keyword.
  3. Increased code complexity: While the override keyword makes the code more explicit and easier to understand, it can also make it more complex, especially in situations involving multiple inheritances.
  4. The overhead of additional checks: Using the override keyword requires the compiler to perform additional checks to ensure the derived class’s virtual function correctly overrides the base class’s virtual function. This can result in some overhead at runtime.
  5. Inability to override a virtual function in the base class with a non-virtual function in the derived class: The override keyword requires that the virtual function in the derived class have the same signature as the virtual function in the base class. This means you cannot override a virtual function in the base class with a non-virtual function in the derived class.

While there are some potential drawbacks to using the override keyword in C++, it is still generally recommended as a best practice, as it can lead to clearer, more maintainable, and more reliable code.

You can also explore Ceil function in C++

Examples of override keyword Use

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

Here is an example that demonstrates the use of the override keyword in C++ to catch errors during compile time:


 
#include <iostream>
class Base {
public:
virtual void foo(int x) {
std::cout << "Base::foo with int parameter: " << x << '\n';
}
};
class Derived : public Base {
public:
void foo(double x) override {
std::cout << "Error: Derived::foo parameter type mismatch\n";
}
};
int main() {
Derived d;
d.foo(3.5); // Should display an error message
return 0;
}
Copy code

The override keyword in the code snippet above is still there to demonstrate the error you mentioned in the original example. When you try compiling this code, the compiler will indicate an error due to the mismatch of parameter type. If you want to see a runtime error message instead, you can remove the override keyword, and it will compile but indicate a runtime error message.

You can also explore Member function in C++

Example 2: Using override keyword to Enforce a consistent inheritance hierarchy

Here is an example that demonstrates the use of the override keyword in C++ to enforce a consistent inheritance hierarchy:


 
#include <iostream>
class Base {
public:
virtual void foo() {
std::cout << "Base::foo\n";
}
};
class Derived1 : public Base {
public:
void foo() override {
std::cout << "Derived1::foo\n";
}
};
class Derived2 : public Derived1 {
public:
void foo() override { // Now with override keyword
std::cout << "Derived2::foo\n";
}
};
int main() {
Derived2 d;
d.foo(); // Output: Derived2::foo
return 0;
}
Copy code

Output

Derived2::foo

In this above code, the Derived2 class’s foo method now includes the override keyword to correctly override the foo method in the Derived1 class, so the code will compile and run successfully.

You can also explore All About Virtual Functions in C++

Example 3: Using override keyword for improved code performance, readability and maintainability.

However, the override keyword in C++ does not directly impact code performance. However, it can help improve code performance by making the code easier to understand and maintain, leading to fewer bugs and performance bottlenecks.

For example, consider the following code:


 
#include <iostream>
class Base {
public:
virtual void foo() {
std::cout << "Base::foo\n";
}
};
class Derived : public Base {
public:
void foo() override {
std::cout << "Derived::foo\n";
}
};
int main() {
Derived d;
Base& b = d;
b.foo(); // Output: Derived::foo
return 0;
}
Copy code

Output

Derived::foo

In the above code, you have a base class Base and a derived class Derived. The Derived class overrides the virtual method foo from the Base class. When you create an object of type Derived and reference it with a reference to Base, the overridden version in Derived is called when foo is invoked.

You can also explore All About C++ Friend Function.

Conclusion

In this way, using the override keyword can help improve code performance by making the code easier to understand and maintain.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio