25

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
David Lobron
  • 1,039
  • 2
  • 12
  • 21

2 Answers2

28

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

4pie0
  • 29,204
  • 9
  • 82
  • 118
  • Thanks very much (and to the others who replied on the main thread). I should have read the standard before asking. :) – David Lobron Sep 12 '14 at 13:32
7

According to the C++ Standard (7.1.2 Function specifiers)

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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335