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.
References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid.
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.
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.
No, references are never null.
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.
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