Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 839
David Lobron Avatar asked Sep 11 '14 21:09

David Lobron


2 Answers

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

like image 192
4pie0 Avatar answered Oct 07 '22 03:10

4pie0


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;

like image 45
Vlad from Moscow Avatar answered Oct 07 '22 05:10

Vlad from Moscow