Search code examples
c++virtual

What is a good convention (or requirement) for the location of the const and virtual keywords in C++?


I know the virtual keyword does not need to be resused in a derived class member function declaration if it overrides a virtual base function but is it good practice to do so to make it clear that it is virtual? Also, what about the presence of the const keyword in declaration and/or definition? I think Alexandrescu mentions something about this but I can't recall what it was?


Solution

  • Your question seems very confused. virtual is optional when overriding a base-class method. const is never optional if you need it. This does not do what you think it does:

    struct A
    {
      virtual void Func() const;
    };
    
    struct B : public A
    {
      virtual void Func();
    };
    

    The struct B has two functions named Func. One of them will be called when the object it is called on is const, and the other will be called when it is not const. Nothing in this code has been overridden; these are two separate virtual functions.

    You cannot just ignore the const and expect everything to work out fine.

    Indeed, this example also shows why you should use virtual when you're overriding in derived classes. In this case, it's fairly obvious that you intended to override a base class function, but you got the function signature wrong. Without the virtual there, there would not be an immediate indication that you intended to override something.

    It's not a huge help, but it's something.

    C++11 provides a better solution (in that it actually solves the problem) with the override pseudo-keyword.

    struct A
    {
      virtual void Func() const;
    };
    
    struct B : public A
    {
      virtual void Func() override; //Gives a compiler error, since it is not overriding a base class function.
    };