Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange default constructor syntax

Tags:

c++

visual-c++

Saw the following in some legacy code:

class A {
    &A() { ... }
}

What "&" is used for? It compiles in VC++ 2008 and looks like default constructor, bug gcc fails to compile it.

like image 482
dimba Avatar asked Nov 08 '10 11:11

dimba


1 Answers

Although syntactically & is allowed in this position in the grammar (it's an example of a declarator that is the sequence: ptr-operator declarator, & being a ptr-operator), semantically it has no meaning and is not allowed here. The fact that it is valid purely from a grammatical point of view may indicate why Visual Studio might accept it.

Examining the possiblities, this declaration looks like a function definition with no return type. 7 [dcl.dcl]/6 says: "Only in function declarations for constructors, destructors and type conversions can the decl-specifier-seq be ommitted." and there being no ~ or operator the only possibility is a constructor declaration.

12.1 [class.ctor] / 1 describes the special declarator syntax used for constructors and it must only be an optional sequence of function-specifiers followed by the constructor's class name. No & or other ptr-operator is allowed before the constructor's class name.

like image 129
CB Bailey Avatar answered Oct 21 '22 05:10

CB Bailey