Passing a pointer by reference in C++ allows us to manipulate the value it's pointing to directly, rather than working with a copy. This can be incredibly useful, especially when dealing with large data structures or complex objects. Let's dive into the details of pass pointer by reference.
![Pass by Reference vs Pass by Pointer in C++ [Differences]](https://i.pinimg.com/originals/b1/e2/a6/b1e2a6e148a41d375b835bf30136b92a.webp)
Before we delve into the intricacies, let's understand what a pointer is. In C++, a pointer is a variable that stores the memory address of another variable. It's a way to indirectly access and manipulate data.

The Basics of Pointers
Pointers are declared using an asterisk (*) before the variable name. The pointer itself is not initialized, but it can be made to point to a variable by using the address operator (&).

Here's a simple example:
```cpp int val = 10; int *ptr = &val; ```
The Need for Pass by Reference

When you pass a pointer to a function, you're actually passing the address it's storing. By default, C++ passes by value, meaning the function receives a copy of the address, not the actual address itself. This is where pass by reference comes in.
To pass by reference, we use a reference variable, which is declared using an ampersand (&) after the data type. Unlike pointers, references must be initialized when they're declared and cannot be changed after that.
Reference Variables

Reference variables allow us to access and manipulate the object they refer to directly. They're sometimes referred to as "alias" variables because they're another name for the same object in memory.
Here's how to declare and initialize a reference variable:
```cpp int val = 10; int &ref = val; ```
Pass Pointer by Reference

To pass a pointer by reference, we declare the function parameter as a pointer to the type of object you're pointing to. Inside the function, you can then directly manipulate the object the pointer is pointing to.
Here's an example:









```cpp void increment(int *ptr) { (*ptr)++; } int main() { int val = 10; int *ptr = &val; increment(ptr); cout << *ptr << endl; // Outputs: 11 } ```
Passing Pointers to Const Objects
What if we want to pass a pointer to a constant object? In this case, we use a pointer to a constant (int const *), which allows us to pass the address of the constant object.
To modify the object pointed to, we need to have a pointer that points to a non-const object. That's where pointer to pointer comes into play.
Pointers to Pointers
Pointers to pointers allow us to modify the address stored in the original pointer. This means we can change what the original pointer is pointing to.
Here's an example:
```cpp void modConst(int *&ptr) { (*ptr)++; } int main() { int val = 10; int *ptr = &val; int const *cptr = ptr; modConst(ptr); cout << *ptr << endl; // Outputs: 11 cout << *cptr << endl; // Outputs: 11 } ```