Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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.</p> <p>You use a pointer when the var can be NULL and client code has to handle that case. You use a reference when you can guarantee a valid/initialised memory address.</p> <p>One example of using pointers is as a member of a class to store a "reference" to some instance that might not be known or able to be initialised at class construction time. However, member references must be initialised at construction time (via initialiser lists) and their assignment cannot be deferred.</p> <p>If you allow a null reference it is then no different to a pointer besides syntax (the same NULL checks would need to take place.)</p> <p><strong>Update:</strong></p> <blockquote> <p>"And, in most OOP languages, objects can be NULL - Pascal, C#, Java, JavaScript, PHP, etc. [...] So why is C++ somehow special and doesn't have a NULL object? Was it just an overlook or an actual decision?"</p> </blockquote> <p>I think you are a bit confused about this. Java and C# etc. might give the impression of <em>"NULL objects"</em>, but these object references are more or less like a C++ pointer with simpler syntax, GC instrumentation and exception throwing. In those languages if you operate on a "Null Object" you will get some kind of exception like <strong>NullReferenceException</strong> (C#). Hell, in Java its called a <strong>NullPointerException</strong>. </p> <p>You have to check for <code>null</code> before you can use them safely. Kind of like C++ pointers (except in most managed languages, pointers are initialised to NULL by default, whereas in C++ its usually up to you to take care of setting the initial pointer value (otherwise undefined/whatever memory was already there)).</p> <p>The C++ view is about having choice, and hence being verbose:</p> <ul> <li>Use a plain pointer to do how you please, checking NULL where necessary. </li> <li>Use references which have a compiler-enforced validity semantic/constraint. </li> <li>Roll your own smart pointers that do bookkeeping and behave whichever way you want them to.</li> <li>Using void pointers (cautiously!) to reference an untyped block of memory if ever required.</li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload