You can't use the assignment operator to bind a reference. It has to be bound when first created. For a class member variable, this means you have to do it in a member initializer list; the body of the constructor is too late.
Example:
#include <iostream> class foo { private: int& x; public: foo(int& other_var) : x(other_var) { } ~foo() { } void print_x() { std::cout << x << std::endl; } }; int main() { int a = 5; foo my_foo(a); my_foo.print_x(); a = 10; my_foo.print_x(); return 0; }
Try on godbolt. It prints out:
5 10
Note that such code, where your object holds a reference to another variable created elsewhere, can be risky. It is up to you to make sure that the referenced int has a lifetime at least as long as the foo object. It can be easy to get this wrong, and the compiler won't help you. Consider for instance:
foo make_a_foo() { int a = 7; foo f(a); return f; } void other_func() { foo g = make_a_foo(); g.print_x(); // undefined behavior! }
Here g.x is a reference to the local variable a from make_a_foo(), whose lifetime ended when make_a_foo() returned.
It may be better after all to make x an ordinary int member variable, instead of a reference, and call a setter function to update its value when needed.
ntot_solsis not a reference.int & ntot_solsthen the linter gives me an error saying that ntot_sols wasn't initialized