Skip to content
Snippets Groups Projects
Commit ea7c88df authored by Marcus Mohr's avatar Marcus Mohr
Browse files

Adds new notebook on pointers and references

parent 906bdb91
Branches
No related tags found
No related merge requests found
%% Cell type:markdown id:eb6a84a9-1411-4a9b-8cbb-c7ed29ecb9c0 tags:
# References
%% Cell type:code id:40de00aa-5b48-420d-8743-099cef5d316a tags:
``` C++17
#include <iostream>
#include <memory>
```
%% Cell type:code id:0579d3c2-3f9d-4904-8762-f1d6cdb2581d tags:
``` C++17
void check() {
int iVal = 1;
int* ptr2int = &iVal;
int** ptr2ptr = &ptr2int;
int& ref2int = iVal;
// int&& ref2ref = ref2int; // this will not work
std::cout << "iVal stores a value of ................. " << iVal << '\n';
std::cout << "iVal resides in memory at address ...... " << std::addressof( iVal ) << "\n\n";
std::cout << "ptr2int stores a value of .............. << " << ptr2int << '\n';
std::cout << "ptr2int resides in memory at address ... << " << &ptr2int << "\n\n";
std::cout << "ptr2ptr stores a value of .............. << " << ptr2ptr << '\n';
std::cout << "ptr2ptr resides in memory at address ... << " << &ptr2ptr << "\n\n";
std::cout << "ref2int stores a value of .............. << " << ref2int << '\n';
std::cout << "ref2int resides in memory at address ... << " << &ref2int << std::endl;
}
```
%% Cell type:code id:3a7034da-2d7f-4429-9853-ffd5e62eefcb tags:
``` C++17
check()
```
%% Output
iVal stores a value of ................. 1
iVal resides in memory at address ...... 0x7ffdf7adbfcc
ptr2int stores a value of .............. << 0x7ffdf7adbfcc
ptr2int resides in memory at address ... << 0x7ffdf7adbfc0
ptr2ptr stores a value of .............. << 0x7ffdf7adbfc0
ptr2ptr resides in memory at address ... << 0x7ffdf7adbfb8
ref2int stores a value of .............. << 1
ref2int resides in memory at address ... << 0x7ffdf7adbfcc
%% Cell type:markdown id:410de220-647d-48f0-93e5-1789d2a72300 tags:
The last two lines clearly show the difference between a pointer and a reference.
While the pointer is a variable with its own memory location, the reference is only an alias of sorts. It occupies the same place in memory and stores the same value as the object it is bound/initialised to.
%% Cell type:code id:df3c18b4-c9b4-4823-8c71-adb4ec5c4593 tags:
``` C++17
```
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment