References & Memory Address

References

In C++, a reference is an alias, or an alternative name, for an existing object. References provide a way to access an object using a different name. Unlike pointers, references cannot be reassigned to refer to a different object after initialization, making them safer and more convenient in many cases.

string food = "Burger";  // food variable
string &meal = food;    // reference to food

Example:

#include <iostream>
#include <string>
using namespace std;

int main() {
  string food = "Burger";
  string &meal = food;

  cout << food << "\n";
  cout << meal << "\n";
  return 0;
}

Output:

Burger
Burger

Memory Address

In C++, you can obtain the memory address of a variable using the address-of operator (&). This operator returns the memory address of the variable it precedes. Memory addresses are represented in hexadecimal format.

Example:

#include <iostream>
#include <string>
using namespace std;

int main() {
  string food = "Burger";

  cout << &food;
  return 0;
}

Output:

0x7ffc188f66b0

    Leave a Reply

    Your email address will not be published.

    Need Help?