C++ References C++ References are Alias of existing variables

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

A Reference in C++ is just an Alias or another name of a variable. Just like most of us can be referred using our passport name and nick name.

References doesn't exist literally and they don't occupy any memory. If we print the address of reference variable it will print the same address as that of the variable its referring to.

int main() {
    int i = 10;
    int &j = i;
    
    cout<<&i<<endl;
    cout<<&b<<endl;
    return 0;
}

In the above example, both cout will print the same address. The situation will be same if we take a variable as a reference in a function

void func (int &fParam ) {
   cout<<"Address inside function => "<<fParam<<endl;
}

int main() {
    int i = 10;
    cout<<"Address inside Main => "<<&i<<endl;    

    func(i);

    return 0;
}

In this example also, both cout will print the same address.

As we know by now that C++ References are just alias, and for an alias to be created, we need to have something which the Alias can refer to.

That's the precise reason why the statement like this will throw a compiler error

int &i;

Because, the alias is not referring to anything.



Got any C++ Question?