Search code examples
c++oopreferencenull

Can a reference be null?


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 not be valid.”

However, I don’t believe this because of following code, which compiles with no error:

class person
{
    public:
    virtual void setage() = 0;
};

int main()
{
    person *object = nullptr;
    person &object1 = *object;
}

Solution

  • 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 ;)