I have read from the Wikipedia that:
“References cannot be null, whereas pointers can; every reference refers to some object, although it may or may n
that would crash your program. Did you try running it? doing *object will deference a null pointer, so in fact your reference never gets assigned.
Well, you can do whatever you want in C++. Another example:
person &object1 = *( reinterpret_cast<person*>(0) );
You are invoking an undefined behavior in the above case, beside the case you mentioned!
Saying person &object1=*object
is not the same thing as saying person &object1=NULL
. Probably the compiler is just not smart enough to find out that you are dereferencing null pointer, but you'll get a runtime error anyway. So they are kind of true still ;)
In your code:
person *object=NULL;
person &object1=*object;
you dereference a NULL pointer, so you get undefined behaviour. And to answer your question, there is no such thing as a NULL reference.
And to address the other part of your question, just because a program compiles, there is no guarantee that it is correct or that it will work. C++ compilers are not required to even attempt to diagnose the kind of error your code contains.
You can have a null reference, not sure why anyone would say otherwise, it is a nasty side effect of some operations. You just can't create one directly.
gcc8 will give a warning about it:
warning: the compiler can assume that the address of 'object1' will never be NULL [-Waddress]
A small demo:
#include <iostream>
class person
{
public:
virtual void setage()=0;
};
int main()
{
person *object=NULL;
person &object1=*object;
if (&object1 == NULL) {
std::cout << "NULL object1" << std::endl;
}
if (!(&object1)) {
std::cout << "NULL object1 " << std::endl;
}
}
Compile and running output:
g++ -std=c++2a -pthread -fgnu-tm -O2 -Wall -Wextra -pedantic -pthread -pedantic-errors main.cpp -lm -latomic -lstdc++fs && ./a.out
main.cpp: In function 'int main()':
main.cpp:14:18: warning: the compiler can assume that the address of 'object1' will never be NULL [-Waddress]
if (&object1 == NULL) { ^
main.cpp:18:19: warning: the compiler can assume that the address of 'object1' will never be NULL [-Waddress]
if (!(&object1)) { ^
NULL object1
NULL object1