Explain in details what is advantage of pointers over references in c++?

  • Pointers can be reassigned while references cannot. Let us see below code
  • pointer.cpp ( below code )
#include<iostream>
using namespace std;

int main() {

	int a = 5;
	int b = 6;
	int *p = &a;
	cout << *p<<endl;
	// reassign
	p = &b;
	cout << *p<<endl;
	return 0;
}

The above program will compile successfully.

  • refere.cpp
#include<iostream>
using namespace std;

int main() {
	int b = 5;
	int c = 4;
	int &a = b;
	b = c; // this not assignment
	cout << a << endl;
	a = 6;
	cout << b <<endl;

	cout << &a<<endl;
	cout << &b<<endl;
	return 0;
}
/*
output
4
6
0x7ffc1b0d4e90
0x7ffc1b0d4e90
*/
  • From the output it is clear that a reference always point to referent b.
  • We cannot do arithmetic operation on reference.
#include<iostream>
using namespace std;

int main() {
	int b = 5;
	int &a = b;
	a = a + 1;
	cout << b;
	return 0;
}

In the above program even if we increments the reference variable a using a = a + 1 , the value of a would not be incremented. Any operation on a would do effect on the variable b as reference variable a is referring to variable b.



Related Contents to follow