Cpp Reference

In C++, references are a powerful feature that allows you to create an alias, or an alternative name, for an existing object. They are used to work with variables indirectly, without creating a copy of the original object. References are commonly used for function parameters, making functions more efficient and allowing them to modify the original data. They are similar to pointers but have some important differences:

1. References:

a. Declaration:
- References are declared using the & symbol, and they must be initialized when declared.

b. Immutability:
- References cannot be changed to refer to a different object once they are initialized.

c. Automatic Dereferencing:
- References are automatically dereferenced, so you don't need to use the dereference operator (*).

        
#include <iostream>

int main() {
    int originalVar = 42;
    int& referenceVar = originalVar;  // Declaring a reference to originalVar

    std::cout << "originalVar: " << originalVar << std::endl;
    std::cout << "referenceVar: " << referenceVar << std::endl;

    referenceVar = 100;  // Modifying referenceVar, which also modifies originalVar

    std::cout << "originalVar after modification: " << originalVar << std::endl;
    std::cout << "referenceVar after modification: " << referenceVar << std::endl;

    return 0;
}
        
    

In this example, we have:

1. Declared an integer variable originalVar and initialized it to 42.

2. Declared a reference variable referenceVar and initialized it to originalVar. Now, referenceVar is an alias for originalVar.

3. Printed the values of both originalVar and referenceVar.

4. Modified referenceVar to 100, which also changes the value of originalVar.

5. Printed the values of both variables again to see the modification.

The output of this code will be:

        
originalVar: 42
referenceVar: 42
originalVar after modification: 100
referenceVar after modification: 100
        
    

As you can see, when we modify referenceVar, it directly modifies originalVar because referenceVar is an alias for originalVar. This is a fundamental characteristic of references in C++. They provide a convenient and safe way to work with existing data without creating copies.