Search code examples
c++overridingvirtual-functions

C++ override specifier without virtual? Does override imply virtual?


Linked question is not the same - and does not even mention override

Edit: The new list of duplicates contains one legitimate duplicate, which I did not find from search.

I was not aware prior to asking this that the choice of whether or not to use virtual in derived class members was going to be a contentious issue for some.


I have just encountered some source code which looks like this:

class A
{
    virtual void method();
};

class B : public A
{
    void method() override;
}

I am unsure of how to interpret this, even after reading this.

Does override imply virtual here? void B::method() is not marked as a virtual function, but it is marked as override. So why does this work, and not result in a compilation error?

Is there any difference between the following? (In class B)

  • void method() override;
  • virtual void method() override;

Solution

  • The answer you're looking for is in https://en.cppreference.com/w/cpp/language/virtual

    If some member function vf is declared as virtual in a class Base, and some class Derived, which is derived, directly or indirectly, from Base, has a declaration for member function with the same name parameter type list (but not the return type) cv-qualifiers ref-qualifiers Then this function in the class Derived is also virtual (whether or not the keyword virtual is used in its declaration) and overrides Base::vf (whether or not the word override is used in its declaration).