Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a reference variable in C++?

What would be a brief definition of a reference variable in C++?

like image 831
sirius79m Avatar asked May 04 '10 14:05

sirius79m


People also ask

What is the reference variable?

A reference variable is a variable that points to an object of a given class, letting you access the value of an object. An object is a compound data structure that holds values that you can manipulate. A reference variable does not store its own values.

Why is reference variable used?

A reference variable provides a new name to the existing variable. It is de-referenced implicitly and does not need a de-referencing operator(*) to retrieve the value referenced.

What is the use of reference variable in C++?

A reference variable provides a new name to an existing variable. It is dereferenced implicitly and does not need the dereferencing operator * to retrieve the value referenced. On the other hand, a pointer variable stores an address. You can change the address value stored in a pointer.

What is the difference between variable and reference variable?

Variables is kinda label for the memory that stores the actual data. Pointers stored the address of the variables. References are alias for the variables.


2 Answers

A reference is an entity that is an alias for another object.

A reference is not a variable as a variable is only introduced by the declaration of an object. An object is a region of storage and, in C++, references do not (necessarily) take up any storage.

As objects and references are distinct groups of entities in C++ so the term "reference variable" isn't meaningful.

like image 182
CB Bailey Avatar answered Oct 04 '22 00:10

CB Bailey


A reference variable provides an alias (alternative name) for a previously defined variable. For example:

float total=100; float &sum = total; 

It means both total and sum are the same variables.

cout<< total; cout << sum; 

Both are going to give the same value, 100. Here the & operator is not the address operator; float & means a reference to float.

like image 38
pankaj bhatt Avatar answered Oct 03 '22 23:10

pankaj bhatt