×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

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 tutorials 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).

Difference between references and pointers in C++

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.

Related Tutorials

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.