In C++, reference and pointer may appear similar at first glance, yet they possess distinct characteristics. A reference serves as an alias for an existing variable, whereas a pointer is a variable that holds the memory address of another variable.
In this post, we will explore the variance between reference and pointer in the C++ programming language. Prior to delving into their distinctions, it is essential to have a solid understanding of references and pointers in C++.
What is a Reference in C++?
A reference in C++ is established using the ampersand (&) symbol. A reference variable serves as an alternative name for a pre-existing variable, providing a means to access the identical memory location under a different identifier. Once a reference is assigned to a variable, it remains fixed and cannot be altered to point to a different variable.
C++ Reference Example
Let's consider an example to demonstrate referencing in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
int main() //main function
{
int i=8; // variable initialization
int &a=i; // creating a reference variable
cout<<"The value of 'i' variable is :"<<a;
return 0;
}
Output:
The value of 'i' variable is :8
Explanation:
In this instance, a reference variable 'a' has been established for the variable 'i'. Following the creation of this reference variable, the value of 'i' can be retrieved using the 'a' variable.
What is a Pointer in C++?
A pointer is a variable storing the memory address of another variable. It can be dereferenced using the (*) operator to retrieve the value at that memory location. Pointers are versatile and can be used with various data types like arrays, primitive data types, as well as custom types such as classes and structures.
C++ Pointer Example
Let's consider a scenario to demonstrate the concept of a pointer in the C++ programming language.
Example
#include <iostream>
using namespace std; //using standard namespace
int main() { //main function
int x = 13, y = 9;
int addition;
int *ptr1 = &x;
int *ptr2 = &y;
addition = *ptr1 + *ptr2;
cout << "First number: " << *ptr1 << endl;
cout << "Second number: " << *ptr2 << endl;
cout << "Addition: " << addition << endl;
return 0;
}
Output:
First number: 13
Second number: 9
Addition: 22
Explanation:
In this instance, we save the memory locations of two integer variables x and y in pointers ptr1 and ptr2. Subsequently, we retrieve their values by dereferencing (ptr1 and ptr2) to compute their sum. Lastly, it displays the initial values and the outcome of the summation.
Key differences between Reference and Pointer
There exist numerous fundamental variances between reference and pointer in the C++ programming language. A few primary disparities are outlined below:
Definition
In C++, a reference variable serves as an alias for a pre-existing variable. It is commonly employed in 'pass by reference' scenarios, where the reference variable is transferred as an argument to a function, allowing the function to operate on the original variable. Conversely, a Pointer is a variable that retains the memory location of another variable, simplifying programming by preserving the memory address of a specific variable.
Declaration
In C++, to create a reference variable, you prefix a variable with the '&' symbol. When this symbol is present in an expression, it signifies an address operator. Conversely, for a pointer variable, you need to declare it by adding a '*' operator before the variable.
Reassignment
In C++, reference variables cannot be reassigned, unlike pointers which can be re-assigned. This feature proves beneficial when handling data structures like linked lists, trees, and more.
Memory Address
When it comes to referencing, both the reference and the original variable point to the identical memory address. A reference consistently points to the original variable it was assigned to and cannot be reassigned to point to a different variable.
Reference Example:
Example
#include <iostream>
using namespace std; //using standard namespace
void func(int &);
int main() //main function
{
int i;
int &a=i;
cout << "The address of 'a' variable is : " <<&a<< endl;
cout << "The address of 'i' variable is : " <<&i<< endl;
return 0;
}
Output:
The address of 'a' variable is : 0x7fff078e7e44
The address of 'i' variable is : 0x7fff078e7e4
Explanation:
The preceding result indicates that both the reference variable and the concrete variable share identical memory locations.
When dealing with pointers, the memory addresses of the pointer variable and the actual variable are distinct.
Pointer Example
Example
#include <iostream>
using namespace std; //using standard namespace
int main() //main function
{
int k;
int *p;
p=&k;
cout<<"The memory address of p variable is :"<<&p;
cout<<"\nThe memory address of k variable is :"<<&k;
return 0;
}
Output:
The memory address of p variable is :0x7ffef9ea3db0
The memory address of k variable is :0x7ffef9ea3dac
NULL Value
In C++, it is not possible to assign a NULL value to a reference variable. Conversely, a pointer variable can indeed be assigned a NULL value.
Indirection
In C++, pointers can include a pointer to pointer, providing multiple levels of indirection.
Pointer Example:
Example
#include <iostream>
using namespace std; //using standard namespace
int main() //main function
{
int *p;
int a=8;
int **q;
p=&a;
q=&p;
cout << "The value of q is : " <<*q<<endl;
return 0;
}
Output:
The value of q is : 0x7fffc17a95f4
Explanation:
In this instance, the pointer 'p' references variable 'a' and 'q' is a double pointer pointing to 'p'. As a result, we can conclude that the content of 'p' represents the memory location of variable 'a', and the content of 'q' represents the memory location of 'p'.
Conversely, in C++, references involve only a single level of indirection.
Reference Example:
Example
#include <iostream>
using namespace std; //using standard namespace
int main() //main function
{
int a=8; // variable initialization
int &p=a; // creating a reference variable for ?a? variable.
int &&q=(p); // Only valid with std::move
return 0;
}
Output:
main.cpp: In function 'int main()':
main.cpp:18:10: error: cannot bind 'int' lvalue to 'int&&'
int &&q=p; // Only valid with std::move
Arithmetic Operations
In C++, calculations can be performed on pointers, a concept known as "Pointer Arithmetic". In contrast, arithmetic operations cannot be carried out on references. There is no such concept as Reference Arithmetic in C++.
Difference between Reference and Pointer in Tabular Form
In this section, we will explore various distinctions between references and pointers presented in a tabular format specifically in the context of C++.
| Features | Reference | Pointer |
|---|---|---|
| Definition | It represents an alias for an existing variable. | It is a variable that contains the memory address of another variable. |
| Syntax | int &ref = var; | int *ptr = &var; |
| Nullability | It cannot be null. | It can be null. |
| Reassignment | Reference cannot be reassigned to another variable. | Pointers can be reassigned to point to different variables. |
| Arguments | The reference is passed using pass-by-reference semantics. | Pointers can simulate pass-by-reference by passing the address of a variable. |
| Memory Address | It is used to share the same address just like the original value. | It contains their own memory address. |
| Indirection | It only provides one level of indirection. | It provides extra levels of indirections. |
Conclusion
In summary, C++ references and pointers offer various means to access and modify data indirectly, yet they serve distinct purposes. References are straightforward and uncomplicated, rendering them appropriate for parameter passing and creating aliases.
On the contrary, pointers offer increased versatility, allowing for null values, reassignment, and managing dynamic memory. The selection between these approaches depends on the specific needs of the situation. References are preferable in scenarios that prioritize simplicity and safety, while pointers are more appropriate when greater control and dynamic functionality are necessary.
Difference between Reference and Pointer in C++ FAQs
1) What is the main difference between a reference and a pointer in C++?
The primary contrast between a reference and a pointer lies in the fact that a reference serves as an alternative name for a variable, while a pointer stores the memory address of the variable.
2) Can Pointers be reassigned in C++?
Yes, in C++, it is possible to reassign pointers to reference different variables.
3) Are references providing more safety than pointers in C++?
Yes, references offer increased safety compared to pointers as they must be initialized and are unable to be null.
4) Can a reference be Null like a pointer in C++?
No, the reference should point to a valid variable. Pointers can have a null value.
5) Do pointers require dereferencing to access the value in C++?
Yes, pointers require the utilization of the * symbol to retrieve the stored data.