Compiler Error 366/

« Compiler-Error-366

Table of Contents

  1. Example

Unlike pointers, references cannot be uninitialized and will cause a compile-time error if this is attemtped.

Because it is impossible to reinitialize a reference, they must be initialized as soon as they are created.

In particular, local and global variables must be initialized where they are defined, and references which are data members of class instances must be initialized in the initializer list of the class's constructor.

C++ Reference

Example

In this example, class X has a local member variable which is a reference to an int, but it will not compile as the reference is uninitialised.

class X 
{
   int &val;
   X() : {}
}

int main () {

  X x;

}

This is the same code again, modified so that the reference is initialized when the object is constructed, by passing a reference to a global variable (i) that has been created.

class X { 
  public: 
    int& val;
    X(int& a) : val(a) {} 
};

int main() { 
  
  int i = 0; 
  X x(i); 

}

All wikipages