Position of virtual keyword in function declaration

It doesn't matter if I put the keyword virtual

in the function declaration before or after the return type?

virtual void DoSomething() = 0;
void virtual DoSomething() = 0;

      

Found syntax void virtual

while refactoring some legacy code and wondered if it compiles at all ...

+3


source to share


4 answers


Both statements are equivalent.
But the first one is more conventional. As usually required fields are kept closer to any syntax (i.e. Function prototype in your example).

virtual

- optional keyword (only required for clean virtual

). However, the return type (here void

) is a required keyword that is always required. So people keep virtual

on the left side and the type is a return

little closer to the function signature.



Another example: I usually see below the 1st syntax code is more popular for the same reason:

const int i = 0;  // 1
int const i = 0;  // 2

      

+5


source


There is no difference between the two, C ++ grammar allows virtual keyword to be displayed both before and after the return type. It's just common practice to put it in the declaration first.



+3


source


Both formats work, but the standard specifies the first format.

Reference:
C ++ 03 7.1 Specifiers

The specifiers that can be used in a declaration are

   decl-specifier:
         storage-class-specifier
         type-specifier
         function-specifier
         friend
         typedef

     decl-specifier-seq:
           decl-specifier-seqopt decl-specifier

      

And further function-specifier

explained in,

7.1.2 Function specifiers

Function specifiers can only be used in function declarations.

 function-specifier:
     inline
     virtual
     explicit

      

+1


source


tested just now:

compiles in both directions.

A regular virtual object is placed before the return type.

read more here: http://msdn.microsoft.com/en-us/library/0y01k918%28v=vs.80%29.aspx

-1


source







All Articles