Initializing a reference to member to NULL in C++

Idov picture Idov · Jan 29, 2012 · Viewed 46.7k times · Source

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?

Answer

Oliver Charlesworth picture Oliver Charlesworth · Jan 29, 2012

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.