Cpp - Reference Reference Introduction

What is a Reference?

A reference is an alias.

When you create a reference, you initialize it with the name of another object, the target.

The reference acts as an alternative name for the target, and anything you do to the reference is really done to the target.

Reference vs Pointer

Pointers are variables that hold the address of another object. References are aliases to an object.

Creating a Reference

You create a reference by writing the type of the target object, followed by the reference operator & followed by the name of the reference.

References can use any legal variable name.

So, if you have an integer variable named someInt, you can make a reference to that variable with the following statement:

int &rSomeRef = someInt; 

rSomeRef is a reference to an integer that is initialized to refer to someInt.


#include <iostream> 
int main() //w  w  w . j  a v a2  s.c o  m
    int intOne; 
    int &rSomeRef = intOne; 
    intOne = 5; 
    std::cout << "intOne: " << intOne << std::endl; 
    std::cout << "rSomeRef: " << rSomeRef << std::endl; 
    rSomeRef = 7; 
    std::cout << "intOne: " << intOne << std::endl; 
    std::cout << "rSomeRef: " << rSomeRef << std::endl; 
    return 0; 


Related Topics