Lesson 11 of 20Object-Oriented C++25 min

References and Pointers

References and pointers both connect your code to an existing object. A reference is an alternative name for an object, while a pointer stores the object’s memory address.

References

Reference example
#include <iostream>
using namespace std;

int main()
{
    int score = 80;
    int& scoreReference = score;

    scoreReference = 95;
    cout << score << endl;

    return 0;
}

Pointers

Pointer example
#include <iostream>
using namespace std;

int main()
{
    int score = 80;
    int* scorePointer = &score;

    cout << "Address: " << scorePointer << endl;
    cout << "Value: " << *scorePointer << endl;

    *scorePointer = 95;
    cout << "Updated score: " << score << endl;

    return 0;
}

Key Symbols

SymbolMeaning
&valueGets the address of a variable.
*pointerDereferences the pointer to access the stored value.
Type*Declares a pointer to a value of that type.
nullptrRepresents a pointer that does not point to an object.
Safety rule

Check that a pointer is not nullptr before dereferencing it.

Practice task

Create an integer, a pointer to that integer, and use the pointer to increase the value by 10.

Lesson Summary

Understand addresses, references, pointers, dereferencing, and nullptr.