How to initialize a class control variable?

Consider the following C ++ code:

#include<iostream> using namespace std; class Test { int &t; public: Test (int &x) { t = x; } int getT() { return t; } }; int main() { int x = 20; Test t1(x); cout << t1.getT() << " "; x = 30; cout << t1.getT() << endl; return 0; } 

When using the gcc compiler

The following error is displayed:
  est.cpp: In constructor 'Test::Test(int&)': est.cpp:8:5: error: uninitialized reference member 'Test::t' [-fpermissive] 

Why does the compiler not directly call the constructor?

+7
source share
2 answers

This is because links can only be initialized in the list of initializers. Use

 Test (int &x) : t(x) {} 

Explanation: the link can only be set once, the place where this happens is a list of initializers. After that, you cannot establish a link, but only assign values ​​to the instance that is referenced. Your code means that you tried to assign something to the instance with the link, but the link was never initialized, so it does not refer to any instance of int and you get an error.

+18
source

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.

+2
source

All Articles