What is the difference between a reference and a pointer in C++?

PointReferencePointer
Must be initializedYesNo
Can be nullNoYes
Can be changed to refer to another variableNoYes
UseLike a normal variableNeeds * and ->
SizeSame as the object (alias)Size of an address
#include <iostream>

int main() {
    int a = 1, b = 2;
    int& ref = a;
    int* ptr = &a;

    ref = 10;              // changes a
    *ptr += 5;             // changes a
    ptr = &b;              // a pointer can point somewhere else
    *ptr = 20;
    std::cout << a << ' ' << b << '\n';
}
Output

15 20

See References and Pointers.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.