Initialising reference in constructor C++
c++, constructor
Solution
There is no such thing as an "empty reference". You have to provide a reference at object initialization. Put it in the constructor's base initializer list:
class c
{
public:
c(int & a) : i(a) { }
int & i;
};
An alternative would be `i(*new int)`, but that'd be terrible.
Edit: To maybe answer your question, you probably just want `i` to be a member object, not a reference, so just say `int i;`, and write the constructor either as `c() : i(0) {}` or as `c(int a = 0) : i(a) { }`.
Problem
I don't think is a duplicate question. There are similar ones but they're not helping me solve my problem. According to this, the following is valid in C++: ``` class c { public: int& i; }; ``` However, when I do this, I get the following error: ``` error: uninitialized reference member 'c::i' ``` How can I initialise successfully do `i=0`on construction? Many thanks.