1
class Test{
    int &b; // no error, can compile
};


int main() {
    int &b; // error: 'b' declared as reference but not initialized 
}

Why I cant have int &b in main function, but can have it in Test class?

  • 1
    Try to create an instance of `Test`, so its `b` member actually exists. – molbdnilo Mar 03 '15 at 23:58
  • I see now: `error: uninitialized reference member in 'class Test'`. – Control 12 Panel Mar 04 '15 at 00:00
  • @Control12Panel: You can use aggregate initialization to create an instance of `Test`. – Kerrek SB Mar 04 '15 at 00:10
  • You'll also get an error if you try to define a constructor for `class Test` that fails to initialize the reference member. In your code, the default constructor's implicit definition doesn't exist because the default constructor isn't odr-used. – Brian Bi Mar 04 '15 at 00:28
  • Somewhat related - Crucial difference between references and pointers - References must be initialized during creation. You may not explicitly initialize a pointer. You cannot assign to a reference, but you can to a pointer. – The Vivandiere Mar 04 '15 at 01:43

3 Answers3

8

A reference must be bound to something at the point where it starts existing.

In the class the declaration specifies that each instance of the class should have this reference. Each such reference starts existing when its class instance is created. At that point some constructor in the class must initialize it, via the constructor's member initializer list, if the reference hasn't been initialized in the declaration (and yours wasn't).

In the function the reference starts existing as the execution passes the declaration. Therefore it must be initialized at this point.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
5

You can't have a reference that doesn't point to anything. Simply defining a class doesn't actually instantiate one; had you tried to create a Test you would have found that would fail as well.

Jonathan Potter
  • 36,172
  • 4
  • 64
  • 79
5

Reference variables need an initializer. Local variables are initialized at the point of declaration. Member variables are initialized in the member initialization list.

Community
  • 1
  • 1
fredoverflow
  • 256,549
  • 94
  • 388
  • 662