What is the difference between a reference and a pointer in C++?
| Point | Reference | Pointer |
|---|---|---|
| Must be initialized | Yes | No |
| Can be null | No | Yes |
| Can be changed to refer to another variable | No | Yes |
| Use | Like a normal variable | Needs * and -> |
| Size | Same 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. |