3

Does it make any difference whether I place the virtual keyword in a function declaration before or after the return value type?

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

Found the void virtual syntax while refactoring some legacy code, and was wondering that it is compiling at all...

Rohit Vipin Mathews
  • 11,629
  • 15
  • 57
  • 112
Ronald McBean
  • 1,417
  • 2
  • 14
  • 27

4 Answers4

5

Both the statements are equivalent.
But the 1st one is more conventional. Because, generally mandatory fields are kept closest to any syntax (i.e. the function prototype in your example).

virtual is an optional keyword (it's needed for pure virtual though). However return type (here void) is a mandatory keyword, which is always required. So people keep virtual on the left most side and the return type a little closer to the function signature.

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

const int i = 0;  // 1
int const i = 0;  // 2
iammilind
  • 68,093
  • 33
  • 169
  • 336
3

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

Nikola Smiljanić
  • 26,745
  • 6
  • 48
  • 60
1

Both the formats work but the standard specifys 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 are explained in,

7.1.2 Function specifiers

Function-specifiers can be used only in function declarations.

 function-specifier:
     inline
     virtual
     explicit
Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
  • But the standard doesn't say anything about the *order* of the specifiers, correct? So it's actually _not_ defined in the standard which of the two alternatives to use. – Ronald McBean Mar 07 '12 at 09:49
  • @RonaldMcBean: Yes, I was looking up for a specific citation but couldn't find any. – Alok Save Mar 07 '12 at 09:51
  • +1 for the standard quotes. I din't know standard specifies all such things also, which we usually take for granted. :0 – iammilind Mar 07 '12 at 10:18
-1

tested just now:

compiles both ways.

usualy virtual is put before return type.

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