Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialising reference in constructor C++

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=0on construction?

Many thanks.

like image 675
ale Avatar asked Jul 04 '11 21:07

ale


People also ask

How do you initialize a reference variable?

If an rvalue reference or a nonvolatile const lvalue reference r to type T is to be initialized by the expression e , and T is reference-compatible with U , reference r can be initialized by expression e and bound directly to e or a base class subobject of e unless T is an inaccessible or ambiguous base class of U .

Can we initialize reference variable?

There are three steps to initializing a reference variable from scratch: declaring the reference variable; using the new operator to build an object and create a reference to the object; and. storing the reference in the variable.


2 Answers

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) { }.

like image 153
Kerrek SB Avatar answered Sep 21 '22 04:09

Kerrek SB


A reference must be initialised to refer to something.

int a; class c { public:    int& i;    c() : i (a) {}; }; 
like image 21
Igor Avatar answered Sep 25 '22 04:09

Igor