struct Div
{
int i;
int j;
};
class A
{
public:
A();
Div& divs;
};
In my constructor definition, I have
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.
For one, you can't have a NULL reference. As second, all variable references in a class must be initialized at construction time.
Plain and simple:
A reference can never be NULL.
class A
{
Div & ref(Div div) { return div; }
public:
A() : divs(ref(Div())) {};
Div& divs;
};
As noted in other posts, references (Div&) cannot be null. So the most straightforward change you can make is to provide a reference in the constructor and initialize your reference member. Like this,
class A
{
public:
A(Div& inDivs);
Div& divs;
};
public A::A( Div& inDivs )
: divs( inDivs )
{}
References have to reference something. There is no such thing as a null reference in the C++ language. If the member may not have a value, then it should be a pointer, or a boost::optional
or some type like that.
A reference must be initialized to reference a valid object.