C++ Pointer to Reference( *& )
The *& symbol also called reference pointer is a combination of a pointer and a reference that is used to declare a pointer to a reference. The * symbol is used to declare a pointer, and the & symbol is used to get the address of a variable thus it creates a reference that point to the value stored by a pointer.
Syntax to Declare Reference Pointer in C++
dataType*& referenceName = pointerVariable;
Here, ptrVariable is a pointer to a variable and referenceName is the name of a pointer to reference.
Example
The below example demonstrates how we can declare and use the pointer to reference in C++.
// C++ program to demonstrate the use of pointer to
// reference
#include <iostream>
using namespace std;
// Function to modify the pointer
void modifyPointer(int*& refPtr)
{
// Allocating new memory
static int newNumber = 99;
refPtr = &newNumber;
}
int main()
{
// define a variable x
int x = 5;
// declare a pointer to variable x
int* ptr = &x;
cout << "Original pointer points to value: " << *ptr
<< endl;
// Pass the pointer to the function by reference
modifyPointer(ptr);
// Now ptr should point to the newNumber in
// modifyPointer
cout << "Pointer now points to value: " << *ptr << endl;
return 0;
}
Output
Original pointer points to value: 5 Pointer now points to value: 99
Difference Between *& and **& in C++
In C++, the *& (pointer to reference) and **&(pointer to pointer reference) symbols are used in the context of pointers and references for manipulating memory addresses and dealing with complex data structures. While they seem similar, they serve different purposes. In this article, we will learn the difference between *& and **& in C++.