C++ References C-PLUS-PLUS
- C++ Introduction
- C++ Syntax
- C++ Output (cout <<)
- C++ Comments
- C++ Variables
- C++ User Input
- C++ Data Types
- C++ Operators
- C++ Strings
- C++ Math
- C++ Booleans
- C++ If Else
- C++ Switch
- C++ While Loop
- C++ Do/While Loop
- C++ For Loop
- C++ Break and Continue
- C++ Arrays
- C++ References
- C++ Pointers
- C++ Functions
- C++ Functions Parameters
- C++ Function Overloading
- C++ OOP
- C++ Classes and Objects
- C++ Class Methods
- C++ Constructors
- Destructors in C++
- C++ Access Specifiers
- C++ Encapsulation
- C++ Inheritance
- C++ Polymorphism
- C++ Files
- C++ Exception Handling
C++ References
C++ References
A reference variable is a "reference" to an existing variable, and it is created with the &
operator.
string &meal = food; // reference to food
Now, we can use either the variable name food
or the reference name meal
to refer to the food
variable.
Example
#include <iostream>
#include <string>
using namespace std;int main() {
string food = "Pizza";
string &meal = food;cout << food << "\n";
cout << meal << "\n";
return 0;
}
Output:
Pizza
Pizza
Memory Address
The &
operator was used to creating a reference variable. But it can also be used to get the memory address of a variable, which is the location of where the variable is stored on the computer.
Note: The memory address is in the hexadecimal form (0x..)
Example
#include <iostream>
#include <string>
using namespace std;int main() {
string food = "Pizza";cout << &food;
return 0;
}
Output:
0x6dfed4