References in C++ | Topic 17 | VU Insider

A reference variable is a "reference" to an existing variable. Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable.

A reference is created by using & operator.

How to create a Reference?

string bike = "Honda"; // bike variable

string &vehicle = bike; // reference to bikecode-box

Now, we can use either the variable name bike or the reference name vehicle to refer to the bike variable.

string bike = "Honda";
string &vehicle = bike;

cout << bike << "\n"; // Outputs Honda
cout << vehicle << "\n"; // Outputs Hondacode-box

Difference between References & Pointers

There are few major differences between References and Pointers:
  • You cannot have NULL references.
  • Once a reference is initialized, it cannot be changed to refer to another while Pointers can be pointed to another object at any time.
  • A reference must be initialized when it is created while Pointers can be initialized at any time.

Post a Comment

Previous Post Next Post