How to initialize the reference member variable of a class?

That is because references can only be initialized in the initializer list. Use

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

To explain: The reference can only be set once, the place where this happens is the initializer list. After that is done, you can not set the reference, but only assign values to the referenced instance. Your code means, you tried to assign something to a referenced instance but the reference was never initialized, hence it’s not referencing any instance of int and you get the error.

Leave a Comment