A pointer can receive a null parameter whereas a reference can’t. You can only use pointer if you want to pass “no object”.
Explicitly passing by pointer allow us to see the whether the object is passes by reference or value at call site.
These are simple example of passing by pointer and passing by reference −
Passing by pointer
Example
#include <iostream>
using namespace std;
void swap(int* a, int* b) {
int c = *a;
*a= *b;
*b = c;
}
int main() {
int m =7 , n = 6;
cout << "Before Swap\n";
cout << "m = " << m << " n = " << n << "\n";
swap(&m, &n);
cout << "After Swap by pass by pointer\n";
cout << "m = " << m << " n = " << n << "\n";
}Output
Before Swap m = 7 n = 6 After Swap by pass by pointer m = 6 n = 7
Passing by reference
Example
#include <iostream>
using namespace std;
void swap(int& a, int& b) {
int c = a;
a= b;
b = c;
}
int main() {
int m =7 , n = 6;
cout << "Before Swap\n";
cout << "m = " << m << " n = " << n << "\n";
swap(m, n);
cout << "After Swap by pass by reference\n";
cout << "m = " << m << " n = " << n << "\n";
}Output
Before Swap m = 7 n = 6 After Swap by pass by reference m = 6 n = 7