My compiler emits this error:
error C2758: 'Test :: t': should be initialized in the initializer list of the base / member of the element
And thatβs exactly what you should do. Links must be initialized in the list of initializers:
#include<iostream> using namespace std; class Test { int &t; public: Test (int &x) : t(x) { } // <-- initializer list used, empty body now int getT() { return t; } }; int main() { int x = 20; Test t1(x); cout << t1.getT() << " "; x = 30; cout << t1.getT() << endl; return 0; }
Explanation:
If the link is not in the initiliazer list, then it is almost impossible for the compiler to detect if the link is initialized. Links must be initialized. Imagine this scenario:
Test (int &x, bool b) { if( b ) t = x; }
Now the developer must decide whether the correct code was actually created. It cannot be. The compiler must ensure that the link is initialized at compile time.
nvoigt
source share