Course Content
C++ Smart Pointers
C++ Smart Pointers
How Are References Different From Pointers?
Understanding references
In the first section, we saw that references are aliases for existing variables. The main thing they do is provide an alternative syntax for accessing the value of an object. If we look under the hood, the memory address of a reference is the same as the memory address of the referenced object.
main
#include <iostream> int main() { int num = 42; int& refNum = num; // Output memory addresses std::cout << "Address of num: " << &num << std::endl; std::cout << "Address of refNum: " << &refNum << std::endl; // Output values std::cout << "Value of num: " << num << std::endl; std::cout << "Value of refNum: " << refNum << std::endl; }
If you run the above code, you will see that both the variable num
and the reference refNum
will have the same values, and the same memory addresses.
A reference is essentially a constant pointer
Another way to think about it is that a reference is essentially a constant pointer. A constant pointer is a pointer that can’t be reassigned to a different dynamic object after initialization. However, a constant pointer has to be dereferenced to get the value of the dynamic object. With references, you don’t have to dereference because you can access the value directly. Let’s consider an example for more clarity:
main
#include <iostream> int main() { // Example with a reference int num1 = 42; int& refNum = num1; // Example with a constant pointer int num2 = 73; int* const ptrNum = &num2; // Attempting to reassign the reference or constant pointer will result in a compilation error // refNum = num2; // Uncommenting this line will just set num1 value to num2 value // ptrNum = &num1; // Uncommenting this line will cause a compilation error // Output values directly through reference and with dereferencing constant pointer std::cout << "Value of num1 through refNum: " << refNum << std::endl; std::cout << "Value of num2 through ptrNum: " << *ptrNum << std::endl; }
In the above code, we are demonstrating many things. First, we are creating a constant pointer and a reference. Then, we show that neither of them can be reassigned. Finally, we print their values: For the constant pointer we have to use *
for dereferencing, but the reference can be accessed directly. Play around with the code to learn more, while following the comments!
Setting to NULL | Can be set to NULL | Cannot be set to NULL |
Address in memory | Has its own address in memory | Does not have its own address in memory |
Initialization | Can be left uninitialized | Must be initialized or causes compiler error |
Pointer to another pointer | Possible | Not possible |
Array creation | Array of pointers can be created | Array of references cannot be created |
Accessing class/struct members | Use -> to access members | Use . to access members |
Thanks for your feedback!