Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a reference to member to NULL in C++

Tags:

Is it possible to initialize a reference member to NULL in c++?
I'm trying to something like this:

class BigClass { private:   Object m_inner; public:   const Object& ReadOnly;   BigClass() : ReadOnly(NULL)   {     Do stuff.   } }; 

I know I can do this if I initialize "ReadOnly" to a real reference of an object, but when I want to put in there "NULL", i get the error:

"cannot convert from 'int' to 'const Object &'

How can I solve this?

like image 209
Idov Avatar asked Jan 29 '12 18:01

Idov


People also ask

Can we initialize reference to null?

No, references cannot be NULL in C++.

Does C initialize pointers to null?

A null pointer is a pointer which points nothing. Some uses of the null pointer are: a) To initialize a pointer variable when that pointer variable isn't assigned any valid memory address yet.

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.


1 Answers

No, references cannot be NULL in C++.1

Possible solutions include:

  • using a pointer instead of a reference.
  • having a dummy Object instance that can be used to indicate "no object".

[1] From the C++11 standard:

[dcl.ref] [...] a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior.

like image 65
Oliver Charlesworth Avatar answered Sep 19 '22 05:09

Oliver Charlesworth