OOP

Differences between reference and pointer

There are key differences between pointers and references in C++. Here’s a breakdown to clarify their characteristics:

Pointers:

Example:

int num = 10;
int* ptr = # // ptr now points to the memory location of num

std::cout << *ptr << std::endl; // Output: 10 (dereferencing ptr to access the value)
ptr = nullptr; // ptr now points to nowhere (null pointer)

References:

Example:

int num = 10;
int& ref = num; // ref now refers to the same memory location as num

std::cout << ref << std::endl; // Output: 10 (directly accessing the value through the reference)
// ref cannot be reassigned to another variable (e.g., ref = 20; would be invalid)

Key Differences:

Feature Pointer Reference
Memory Location Stores memory address Refers to existing variable’s memory location
Reassignment Can be reassigned to different addresses Cannot be reassigned after initialization
Null Value Can be null Must be initialized with a valid variable
Dereferencing Needed to access the pointed-to value Not needed, directly access the value

Choosing Between Pointers and References:

Summary:

Pointers provide more flexibility and control over memory management, while references offer a safer and more convenient way to work with existing variables. The choice between them depends on your specific needs and the context of your code.