Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the position of the virtual keyword in a function declaration matter?

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;

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

like image 247
Ronald McBean Avatar asked Oct 29 '25 10:10

Ronald McBean


2 Answers

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
like image 116
iammilind Avatar answered Oct 31 '25 01:10

iammilind


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.

like image 22
Nikola Smiljanić Avatar answered Oct 31 '25 01:10

Nikola Smiljanić