Reputation: 11830
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.
Upvotes: 38
Views: 80635
Reputation: 1
Reference should be initialised either by passing data to constructor or allocate memory from heap if you want to initialize in default constructor.
class Test
{
private:
int& val;
std::set<int>& _set;
public:
Test() : val (*(new int())),
_set(*(new std::set<int>())) { }
Test(int &a, std::set<int>& sett) : val(a), _set(sett) { }
};
int main()
{
cout << "Hello World!" << endl;
Test obj;
int a; std::set<int> sett;
Test obj1(a, sett);
return 0;
}
Thanks
Upvotes: -2
Reputation: 15968
Apart from the sweet syntax, a key feature of references is that you are pretty sure that it always point to a value (No NULL value).
When designing an API, it forces user to not send you NULL. When consuming an API, you know without reading the doc that NULL is not an option here.
Upvotes: 5
Reputation: 477570
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) { }
.
Upvotes: 48
Reputation: 35089
References have to be initialized upon creation. Thus you have to initialize it when the class is created. Also you have to provide some legal object to reference.
You have to use the initializer in your constructor:
class c {
public:
c(const int& other) : i(other) {}
int& i;
};
Upvotes: 0