The override Keyword in C++ Explained

What does the override keyword do in C++ when used with class methods?

The override keyword in C++ is a special specifier that you can add at the end of a member function declaration or definition in a derived class. Its purpose is to clearly state your intent that this function is meant to override a virtual function from one of its base classes.

// Base class
class Base {
public:
  virtual void DoSomething() { /* ... */ }
  virtual void AnotherFunc(int x) { /* ... */ }
  void NonVirtualFunc() { /* ... */ }
};

// Derived class
class Derived : public Base {
public:
  // Correctly overrides Base::DoSomething
  void DoSomething() override { /* ... */ } 

  // Also correct
  virtual void AnotherFunc(int x) override { /* ... */ } 

  // ERROR: NonVirtualFunc is not virtual in Base
  // void NonVirtualFunc() override {} // Won't compile

  // ERROR: Typo in name, no Base function matches
  // void DoSomethang() override {} // Won't compile

  // ERROR: Different signature, no Base function matches
  // void AnotherFunc(float x) override {} // Won't compile
};

Benefits of Using override

Using override provides two significant benefits:

Compile-Time Safety

This is the primary advantage. The compiler verifies that your function actually overrides a base class virtual function. If it doesn't match any base class virtual function signature precisely (same name, same parameter types, same const/volatile qualification, same ref-qualifiers), the compiler will generate an error.

Without override****: If you make a typo in the function name or its parameters, you might accidentally create a new, unrelated function in the derived class instead of overriding the base class one. Your code will compile, but polymorphism won't work as expected - calls through a base class pointer might call the base version instead of your intended derived version.

class DerivedOops : public Base {
public:
  // TYPO! No override keyword used.
  // This compiles, but creates a NEW function,
  // it DOES NOT override Base::DoSomething()!
  virtual void DoSomethang() { 
    // ... oops ...
  }
};

Base* ptr = new DerivedOops();
ptr->DoSomething(); // Calls Base::DoSomething(),
                    // NOT DerivedOops::DoSomethang()!

With override****: If you make the same typo but include override, the compiler immediately tells you something is wrong.

class DerivedSafe : public Base {
public:
  // TYPO! But override keyword IS used.
  virtual void DoSomethang() override {
    // ...
  }
  // COMPILER ERROR: 'DoSomethang' marked override
  // but does not override any base class method.
};

Improved Readability and Maintainability

The override keyword clearly documents the programmer's intention. Anyone reading the code immediately knows that this function is part of a polymorphism hierarchy and is specifically designed to replace a base class implementation. This makes the code easier to understand and safer to modify later.

When to Use It

You should use override whenever you intend for a function in a derived class to override a virtual function from a base class. It's considered modern C++ best practice. While not strictly required for overriding to occur (if the signature matches perfectly), the safety net and clarity it provides are invaluable.

Note that override can only be used on virtual functions in derived classes. Trying to use it on non-virtual functions or on functions in a class with no base classes will result in a compiler error.

Creating SDL2 Buttons

Learn to create interactive buttons in SDL2 and manage communication between different UI components.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Understanding Incomplete Types in C++ Forward Declarations
What is an "incomplete type" in C++ and why does it prevent calling functions in a header file?
C++ Dangling References: Lifetimes and Undefined Behavior
What happens if an object is destroyed before a reference to it, like if UI is destroyed before Button?
How SDL_PushEvent() Works in SDL2
What exactly does SDL_PushEvent() do in SDL2, and where does the event go?
Handling Right and Middle Mouse Clicks in SDL2
How would I handle right-clicks or middle-clicks on an SDL2 button?
Pointers vs References for Component Communication in C++: Safety and Use Cases
Is passing raw pointers safer or better than references for parent/child communication in C++?
Adding Tooltips to SDL Buttons
Is it possible to add tooltips to SDL buttons when hovering?
Creating Image Buttons in SDL
Can I create a button with an image instead of a solid color?
Animating Button Clicks in SDL
How would I implement a button that triggers an animation when clicked?
Adding Keyboard Shortcuts to SDL Buttons
How can I add keyboard shortcuts to trigger button actions?
Changing Button Shape on Interaction
Can I implement a button that changes shape when hovered or clicked?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant