C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C++ programming language

Difference between references and pointers in C++ programming language

Learn: References and Pointers in C++, what are the differences between a pointer variable or a reference variable in C++ programming language, what should we used?

There are few posts related to references are pointers based, I would recommend to read them first (you didn't read), those are:

In this post, I am going to discuss about the differences between references and pointers (reference variables and pointer variables).

Since, a reference and a pointer both are almost same, but they have few differences too, the differences are:

1) A reference is a const pointer. Hence reference is initialized that cannot be made to refer to another variable, whereas pointer can be modified at run time.

2) With the pointers, pointer to pointer is possible but reference to reference is not meaning full. When we try to assign a reference to a reference the new reference starts referring to the same variable the first reference is referring to.

3) While using pointers, we need to explicitly de-reference the pointer using "value at address" operator (*), but with the reference there is no such need to dereference, because reference gets automatically de-referenced.

Reference to Reference demonstration in C++

#include <iostream>
using namespace std;

int main()
{
	int a=100;
	int &b=a;
	int &c=b;   //reference to reference
	
	cout<<"b: "<<b<<",c: "<<c<<endl;
	return 0;
}

Output

b: 100,c: 100

In above example, c is reference to reference b and both b and c refer to the variable a;

Pointer to pointer demonstration in C++

#include <iostream>
using namespace std;

int main()
{
	int a=100;
	int *pa = &a;
	int **ppa = &pa;
	
	cout<<"pa: "<<pa<<", ppa: "<<ppa<<endl;
	
	return 0;
}

Output

pa: 0x7fff27d716e4, ppa: 0x7fff27d716d8

In this example, pa is pointing to the address of a and ppa is pointing to the address of pa.

Read more: Pointer to Pointer (Double Pointers in C)

Advantage of references over pointers

While using pointers we need to explicitly de-reference the pointer using ‘value at address’ operator (*). While using reference we don’t have to use any operator since a reference gets automatically de-referenced.
Read in details: Advantages of references over pointers.

Advantage of pointers over references

Reference being a const pointer cannot be reassigned while pointers can be reassigned.









COMMENTS