Mark As Completed Discussion

References in C++

In C++, a reference is an alias for an existing object or variable. It allows you to access and manipulate the object or variable using a different name.

Declaring References

You can declare a reference by using the & symbol followed by the name of the reference. For example:

TEXT/X-C++SRC
1int num = 10;
2int& ref = num;

In this example, ref is a reference to the variable num. Any changes made to ref will also affect num, and vice versa.

Difference between References and Pointers

References and pointers are commonly used in C++ for indirection, but they have some important differences:

  • References must be initialized when they are declared, and they cannot be reassigned to point to a different object or variable.
  • Pointers, on the other hand, can be assigned to point to different objects or variables.

In the example code above, ref is initialized with num, and it cannot be reassigned to point to a different variable.

When to Use References

References are often used in C++ to pass arguments to functions by reference, allowing the function to modify the original object or variable. They can also be used to create more readable and expressive code when working with complex data structures.

Example

Here's an example that demonstrates the use of references:

TEXT/X-C++SRC
1int main() {
2  int num = 10;
3  int& ref = num;
4
5  cout << "Value of num: " << num << endl;
6  cout << "Value of ref: " << ref << endl;
7  cout << "Address of num: " << &num << endl;
8  cout << "Address of ref: " << &ref << endl;
9
10  return 0;
11}

In this example, we declare an integer variable num and a reference ref to num. We then output the values of num, ref, and their memory addresses.

Executing the code will output:

SNIPPET
1Value of num: 10
2Value of ref: 10
3Address of num: [memory address]
4Address of ref: [same memory address as num]
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment