Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialization of reference member requires a temporary variable C++

struct Div
{
   int i;
   int j;
};   

class A
{
public:
    A();
    Div& divs;
};

In my constructor definition, I have the following implementation

A::A(): divs(NULL)
{}

I get the following error:

Error72 error C2354: 'A::divs' : initialization of reference member requires a temporary variable

like image 866
aajkaltak Avatar asked Nov 09 '09 14:11

aajkaltak


People also ask

How do you initialize a 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.

Can we initialize reference variable in C++?

An rvalue reference can be initialized with an lvalue in the following contexts: A function lvalue. A temporary converted from an lvalue. An rvalue result of a conversion function for an lvalue object that is of a class type.

How do you initialize const and reference member variables?

To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.


1 Answers

A reference must be initialised to refer to something; it can't refer to nothing, so you can't default-construct a class that contains one (unless, as others suggest, you define a global "null" value). You will need a constructor that is given the Div to refer to:

explicit A(Div &d) : divs(d) {}

If you want it to be able to be "null", then you need a pointer, not a reference.

like image 85
Mike Seymour Avatar answered Nov 03 '22 11:11

Mike Seymour