Should a virtual c++ method implementation in .cpp file be marked virtual?

David Lobron picture David Lobron · Sep 11, 2014 · Viewed 13.2k times · Source

I have a virtual C++ method that I'm defining in a .h file and implementing in a .cc file. Should the implementation in the .cc file be marked virtual, or just the declaration in the .h file? E.g., my header has:

virtual std::string toString() const;

The method is implemented in my .cc:

std::string
MyObject::toString() const {
   [implementation code]
}

Should the implementation be marked virtual, or is the above code OK? Does it matter?

Answer

4pie0 picture 4pie0 · Sep 11, 2014

C++ Standard n3337 § 7.1.2/5 says:

The virtual specifier shall be used only in the initial declaration of a non-static class member function;

Keyword virtual can be used only inside class definition, when you declare (or define) the method. So... it can be used in implementation file but if it is still in class definition.

Example:

class A {
    public:
    virtual void f();
};

virtual void A::f() {}  // error: ‘virtual’ outside class declaration
                        // virtual void A::f() {}

int main() {
    // your code goes here
    return 0;
}

http://ideone.com/eiN7bd