The 'override' keyword in C++ is used to ensure that functions in derived classes correctly override virtual functions in the base class. Using the 'override' keyword enables the compiler to verify at compile time that the function in the derived class actually overrides a virtual function in the base class, which helps prevent errors due to spelling mistakes or mismatched function signatures.
For example, suppose we have a base class and a derived class, with a virtual function in the base class:
cppclass Base { public: virtual void foo(int x) { std::cout << "Base foo: " << x << std::endl; } }; class Derived : public Base { public: void foo(int x) override { std::cout << "Derived foo: " << x << std::endl; } };
In this example, the derived class Derived uses the 'override' keyword to indicate that its foo function is intended to override the foo function in the base class Base. If the signature of the foo function in the Derived class is changed to void foo(double x), the compiler will report an error because there is no matching virtual function to override, which helps in promptly identifying potential errors.