Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A reference can not be NULL or it can be NULL?

Tags:

c++

oop

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.

like image 283
Zia ur Rahman Avatar asked Jan 29 '10 20:01

Zia ur Rahman


People also ask

Can a reference be null?

References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid.

Can references be null or invalid?

Now to answer your question: yes it is possible that a reference be null or invalid. You can test for a null reference ( T& t = ; if (&t == 0) ) but it should not happen >> by contract a reference is valid.

What is there is no null reference?

Because a reference carries the semantic that it points to a valid memory address that never changes; i.e. that dereferencing it is safe/defined and so no NULL checks are required. References cannot be reassigned by design. You use a pointer when the var can be NULL and client code has to handle that case.

Can a reference parameter be null?

No, references are never null.


1 Answers

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.

like image 127
Charles Eli Cheese Avatar answered Oct 20 '22 21:10

Charles Eli Cheese