- C++ Introduction
- C++ Getting Started
- C++ Syntax
- C++ Output (Print Text)
- C++ Comments
- C++ Variables
- C++ Declare Multiple Variables
- C++ Identifiers
- C++ User Input
- C++ Data Types
- C++ Operators
- C++ Strings
- C++ Math
- C++ Booleans
- C++ Conditions
- C++ Switch
- C++ While Loop
- C++ For Loop
- C++ Break And Continue
- C++ Arrays
- C++ References
- C++ Pointers
- C++ Functions
- C++ Function Overloading
- C++ OOP
- C++ Classes And Objects
- C++ Class Methods
- C++ Constructors
- C++ Access Specifiers
- C++ Encapsulation
- C++ Inheritance
- C++ Multilevel Inheritance
- C++ Multiple Inheritance
- C++ Inheritance Access
- C++ Polymorphism
- C++ Files
- C++ Exceptions
- C++ How To Add Two Numbers
C++ References
Creating 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
string &meal = food;
cout << food << "\n"; // Outputs Pizza
cout << meal << "\n"; // Outputs Pizza
Practice Excercise Practice now
C++ Memory Address
In the example from the previous page, the &
operator was used to create 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.
When a variable is created in C++, a memory address is assigned to the variable. And when we assign a value to the variable, it is stored in this memory address.
To access it, use the &
operator, and the result will represent where the variable is stored:
Example
cout << &food; // Outputs 0x6dfed4
Note: The memory address is in hexadecimal form (0x..). Note that you may not get the same result in your program.
And why is it useful to know the memory address?
References and Pointers (which you will learn about in the next chapter) are important in C++, because they give you the ability to manipulate the data in the computer's memory - which can reduce the code and improve the performance.
These two features are one of the things that make C++ stand out from other programming languages, like Python and Java.
Practice Excercise Practice now
Products
Partner
Copyright © RVR Innovations LLP 2024 | All rights reserved - Mytat.co is the venture of RVR Innovations LLP