Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.”

But I don’t believe because of following code, look at it, compiler gives no error:

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

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

Please elaborate this point.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
225 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...