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?
No, references cannot be NULL in C++.
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.
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.
No, references cannot be NULL
in C++.1
Possible solutions include:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With