Pointers and references in C++

Hi folks, today I’m going to explain conept of pointers and references in C++ in very simple terms.

Pointers:

Pointers variable are used to store address of another variable. And it needs to dereferenced with * operator in order to access the value stored at given location. We define pointers something like this:

Declaration and Initialization:

<data_type> *<pointer_variable_name> = <address_of_another_variable>

int item = 10;

int *ptr = &item; // address of item;

Now if you want to access or update value of pointer variable, then you have to dereference it first with * operator. By dereferencing pointer, you will be able to access and modify its value.

std::cout << *ptr << std::endl; // 10

*ptr = 39;

std::cout << item << "-" << *ptr << "-" << ptr;   //  39 - 39 - address_of_variable

References

Reference variables are an alias of a given vairable. Like a pointer variable it also stores memory address of a variable. And thats why you can change the value of referenced variable directly. In simple word, you can consider it as a giving one more name to your exisiting variable, that’s why you can modify and access value of referenced variable just like normal variable.

Declaration and Initialization:

<data_type> &variable_name = old_variable_name;

int x = 20;

int &y = x; // Refrence variable

// accessing and modifying

y = 10;

cout << y; // 10

Difference Between Pointer and Reference:

Pointers are separate variable used to store memory address of given variable, while reference is just an alias or new name given to existing variable.

  • Pointers can be reassigned to point to another variables address, while references variable can’t be reassigned.
  • Pointers have to use * to access the value of the variable that they are pointing to, while reference can directly access value of the variable that they are refrencing to.

That’s it for today, i hope you liked this article. If yes then please share this with you friend.

Thanks to read:)

Leave a Comment