Synopsis: | When overriding a (virtual) function from a base class, the derived class should give the same const modifier to the function. |
Language: | C++ |
Severity Level: | 2 |
Category: | Object Oriented Programming |
Description: |
This prevents unintentionally calling the function of the base class. class Base { public: // Methods virtual void f() const; }; class Derived : public Base { public: // Methods virtual void f(); //This is not an override, not allowed !!! }; The reason is when a client attempts a polymorphic call to f() through a const pointer or const reference to Base, it will call Base::f() and not Derived::f(), which is syntactically correct but probably surprising. The same care should be used when overriding a function with a parameter that is a pointer or reference to const. |