bobobobo
bobobobo

Reputation: 67244

Declaration of reference variable requires an initializer

I have reduced my real program to a toy example.

Say I have the following code:

struct A
{
  A( string i ) { }
  A( string *i ) { }
};

int main()
{
  string s;
  A("HELLO"); // Works
  A(&s); // XCode: Declaration of reference variable 's' requires an initializer
  // Visual Studio: error C2040: 's': 'A &' differs in levels of indirection from 'std::string'
}

I don't understand the error message. What does XCode mean "Declaration of reference variable 's' requires an initializer"? Why does A("HELLO"); work while A(&s) does not?

Upvotes: 4

Views: 6027

Answers (1)

Fureeish
Fureeish

Reputation: 13424

This is a phenomenon called most-vexing parse.

C++ treats A(&s); as a declaration of a variabled called s, whose type is A&. This won't work for several reasons:

  • References need to be initialized, and you are not initializing s in this example (note: this s is not the same s as the one from 2 lines before).

  • You already have a variable called s in the same scope, so this would be a redefinition.

To create an even smaller example, take a look at these two, equivalent lines of code that both declare a variable called x of type int:

int x;
int(x);

To fix the issue, you can simply use a proper declaration that uses the desired constructor, which doesn't suffer from the most-vexing parse problem:

A x1(&s); // this
auto x2 = A(&s); // or this
A{&s}; // or this, just to create a temporary

Upvotes: 7

Related Questions