What is a Reference? - C++ Data Type

C++ examples for Data Type:Reference

Introduction

References give you almost all the power of pointers with a much easier syntax.

A reference is an alias.

When you create a reference, you initialize it with the name of 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.

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

Creating a Reference

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

int &rSomeRef = someInt; 

Demo Code

#include <iostream> 
 
int main() /*from  w  ww  . java2  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; 
}

Result


Related Tutorials