Click here to Skip to main content
16,018,417 members
Articles / Programming Languages / C++

An Insight to References in C++

Rate me:
Please Sign up or sign in to vote.
3.52/5 (46 votes)
18 Apr 2006CPOL4 min read 176.7K   37   73
How C++ Compiler handles References

Introduction

I choose to write about references in C++ because I feel most of the people have misconceptions about references. I got this feeling because I took many C++ interviews and I seldom get correct answers about references in C++.

What is meant by references in C++? A reference is generally thought of as an aliasing of the variable it refers to. I hate the definition of references being an alias of a variable in C++. In this article, I will try to explain that there is nothing known as aliasing in C++.

Background

Both in C and in C++, there are only two ways by which a variable can be accessed, passed, or retrieved. The two ways are: 

  1. Accessing/passing variable by value
  2. Accessing/Passing variable by address - In this case pointers will come into the picture

There is no 3rd way of accessing/passing variables. A reference variable is just another pointer variable which will take its own space in memory. The most important thing about the references is that it's a type of pointer which gets automatically dereferenced (by compiler). Hard to believe? Let's see....

A Sample C++ Code using References

Lets write a simple C++ code which will use references:

C++
#include <iostream.h>
int main()
{
    int i = 10;   // A simple integer variable
    int &j = i;   // A Reference to the variable i
    
    j++;   // Incrementing j will increment both i and j.

    // check by printing values of i and j
    cout<<  i  <<  j  <<endl; // should print 11 11

    // Now try to print the address of both variables i and j
    cout<<  &i  <<  &j  <<endl; 
    // surprisingly both print the same address and make us feel that they are
    // alias to the same memory location. 
    // In example below we will see what is the reality
    return 0;
}

References are nothing but constant pointers in C++. A statement int &i = j; will be converted by the compiler to int *const i = &j; i.e. References are nothing but constant pointers. They need initialization because constants must be initialized and since the pointer is constant, they can't point to anything else. Let's take the same example of references in C++ and this time we will use the syntax that the compiler uses when it sees references.

A Sample C++ Code using References (Compiler Generated Syntax)

C++
#include <iostream.h>
int main()
{
    int i = 10;   		// A simple integer variable
    int *const j = &i;   	// A Reference to the variable i
    
    (*j)++;   		// Incrementing j. Since reference variables are 
			// automatically dereferenced by compiler

    // check by printing values of i and j
    cout<<  i  <<  *j  <<endl; // should print 11 11
    // A * is appended before j because it used to be reference variable
    // and it should get automatically dereferenced.
    return 0;
}

You must be wondering why I skipped the printing of address from the above example. This needs some explanation. Since reference variables are automatically dereferenced, what will happen to a statement like cout << &j << endl;. The compiler will convert the statement into cout << &*j << endl; because the variable gets automatically dereferenced. Now &* cancels each other. They become meaningless and cout prints the value at j which is nothing but the address of i because of the statement int *const j = &i;.

So the statement cout << &i << &j << endl; becomes cout << &i << &*j << endl; which is similar to printing the address of i in both the cases. This is the reason behind the same address being displayed while we try to print normal variables as well as reference variables.

A Sample C++ Code using Reference Cascading

Here we will try to look at a complex scenario and see how references will work in cascading. Let's follow the code below:

C++
#include <iostream.h>
int main()
{
    int i = 10; // A Simple Integer variable
    int &j = i; // A Reference to the variable
    // Now we can also create a reference to reference variable. 
    int &k = j; // A reference to a reference variable
    // Similarly we can also create another reference to the reference variable k
    int &l = k; // A reference to a reference to a reference variable.

    // Now if we increment any one of them the effect will be visible on all the
    // variables.
    // First print original values
    // The print should be 10,10,10,10
    cout<<  i  <<  ","  <<  j  <<  ","  <<  k  <<  ","  <<  l  <<endl;
    // increment variable j
    j++; 
    // The print should be 11,11,11,11
    cout<<  i  <<  ","  <<  j  <<  ","  <<  k  <<  ","  <<  l  <<endl;
    // increment variable k
    k++;
    // The print should be 12,12,12,12
    cout<<  i  <<  ","  <<  j  <<  ","  <<  k  <<  ","  <<  l  <<endl;
    // increment variable l
    l++;
    // The print should be 13,13,13,13
    cout<<  i  <<  ","  <<  j  <<  ","  <<  k  <<  ","  <<  l  <<endl;
    return 0;
}

A sample C++ Code Using Reference Cascading (Compiler Generated Syntax)

Here we will see if we won't depend upon the compiler to generate constant pointers in place of reference and auto dereferencing the constant pointer, we can achieve the same results.

C++
#include <iostream.h>
int main()
{
    int i = 10;         // A Simple Integer variable
    int *const j = &i;     // A Reference to the variable
    // The variable j will hold the address of i

    // Now we can also create a reference to reference variable. 
    int *const k = &*j;     // A reference to a reference variable
    // The variable k will also hold the address of i because j 
    // is a reference variable and 
    // it gets auto dereferenced. After & and * cancels each other 
    // k will hold the value of
    // j which it nothing but address of i

    // Similarly we can also create another reference to the reference variable k
    int *const l = &*k;     // A reference to a reference to a reference variable.
    // The variable l will also hold address of i because k holds address of i after
    // & and * cancels each other.

    // so we have seen that all the reference variable will actually holds the same
    // variable address.

    // Now if we increment any one of them the effect will be visible on all the
    // variables.
    // First print original values. The reference variables will have * prefixed because 
    // these variables gets automatically dereferenced.

    // The print should be 10,10,10,10
    cout<<  i  <<  ","  <<  *j  <<  ","  <<  *k  <<  ","  <<  *l  <<endl;
    // increment variable j
    (*j)++; 
    // The print should be 11,11,11,11
    cout<<  i  <<  ","  <<  *j  <<  ","  <<  *k  <<  ","  <<  *l  <<endl;
    // increment variable k
    (*k)++;
    // The print should be 12,12,12,12
    cout<<  i  <<  ","  <<  *j  <<  ","  <<  *k  <<  ","  <<  *l  <<endl;
    // increment variable l
    (*l)++;
    // The print should be 13,13,13,13
    cout  <<  i  <<  ","  <<  *j  <<  ","  <<  *k  <<  ","  <<  *l  <<endl;
    return 0;
}

A Reference Takes its Own Space in Memory

We can see this by checking the size of the class which has only reference variables. The example below proofs that a C++ reference is not an alias and takes its own space into the memory.

C++
#include <iostream.h>

class Test
{
    int &i;   // int *const i;
    int &j;   // int *const j;
    int &k;   // int *const k; 
};

int main()
{    
    // This will print 12 i.e. size of 3 pointers
    cout<<  "size of class Test = "  <<   sizeof(class Test)  <<endl;
    return 0;
}

Conclusion

I hope that this article explains everything about C++ references. However I'd like to mention that C++ standard doesn't explain how reference behaviour should be implemented by the compiler. It's up to the compiler to decide, and most of the time it is implemented as a constant pointer.

Additional Notes to Support this Article

In the discussion forums for this article, people were having concerns that References are not constant pointers but aliases. I am writing one more example to support this fact. Look carefully at the example below:

C++
#include <iostream.h>

class A
{
public:
	virtual void print() { cout<<"A.."<<endl; }
};

class B : public A
{
public:
	virtual void print() { cout<<"B.."<<endl; }
};

class C : public B
{
public:
	virtual void print() { cout<<"C.."<<endl; }
};

int main()
{
	C c1;
	A &a1 = c1;
	a1.print(); // prints C

 	A a2 = c1;
	a2.print(); // prints A
	return 0;
}

The example using references supports the virtual mechanism, i.e. looking into the virtual pointer to get the handle to correct function pointer. The interesting thing here is how the virtual mechanism is supported by the static type which is simply an alias. Virtual mechanism is supported by dynamic information which will come into the picture only when a pointer is involved. I hope this will clarify most of the doubts.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India
A programmer by heart since 1998. Written code in C++, Java, JavaScript, Python & Ruby, Worked on Stack Development to Web Development. Data Specialist with SQL and NoSQL DBs

Comments and Discussions

 
QuestionPointer to a reference. Pin
Anitesh Kumar4-Jun-12 1:52
Anitesh Kumar4-Jun-12 1:52 
AnswerRe: Pointer to a reference. Pin
IshanB9-Jul-12 4:18
IshanB9-Jul-12 4:18 
GeneralReference Variable Disadvantages Pin
ArchangelOfTheElectronicWorld23-Jan-08 23:11
ArchangelOfTheElectronicWorld23-Jan-08 23:11 
GeneralWords fail me Pin
trelliot27-Apr-06 15:29
trelliot27-Apr-06 15:29 
Generalreference != const pointer Pin
Rob Hemstede19-Apr-06 5:50
Rob Hemstede19-Apr-06 5:50 
GeneralRe: reference != const pointer Pin
Iftahh19-Apr-06 22:51
Iftahh19-Apr-06 22:51 
GeneralRe: reference != const pointer Pin
itsdkg19-Apr-06 23:18
itsdkg19-Apr-06 23:18 
GeneralRe: reference != const pointer Pin
Rob Hemstede19-Apr-06 23:54
Rob Hemstede19-Apr-06 23:54 
GeneralRe: reference != const pointer Pin
nutty26-Apr-06 3:20
nutty26-Apr-06 3:20 
GeneralRe: reference != const pointer Pin
jefito9-Apr-21 2:39
jefito9-Apr-21 2:39 
GeneralJust an alias Pin
maihem19-Apr-06 2:56
maihem19-Apr-06 2:56 
GeneralGreat topic, style points (2) Pin
Shawn Poulson19-Apr-06 2:17
Shawn Poulson19-Apr-06 2:17 
GeneralRe: Great topic, style points (2) Pin
Iftahh19-Apr-06 22:55
Iftahh19-Apr-06 22:55 
GeneralConfusing article Pin
jefito15-Mar-06 3:43
jefito15-Mar-06 3:43 
GeneralRe: Confusing article Pin
itsdkg15-Mar-06 18:14
itsdkg15-Mar-06 18:14 
GeneralRe: Confusing article Pin
Ilya Lipovsky16-Mar-06 4:38
Ilya Lipovsky16-Mar-06 4:38 
GeneralRe: Confusing article Pin
Ilya Lipovsky16-Mar-06 6:46
Ilya Lipovsky16-Mar-06 6:46 
GeneralRe: Confusing article Pin
itsdkg16-Mar-06 19:13
itsdkg16-Mar-06 19:13 
GeneralRe: Confusing article Pin
jefito21-Mar-06 13:18
jefito21-Mar-06 13:18 
GeneralRe: Confusing article Pin
itsdkg22-Mar-06 1:06
itsdkg22-Mar-06 1:06 
GeneralRe: Confusing article Pin
jefito23-Mar-06 7:30
jefito23-Mar-06 7:30 
GeneralRe: Confusing article Pin
Ilya Lipovsky24-Mar-06 9:16
Ilya Lipovsky24-Mar-06 9:16 
Hi Jeff,

jefito wrote:
nt array[10] = {0}; // simple array
int& ri = array[3]; // reference to array member
ri = 4; // change array member through reference

It should be fairly straightforward for a compiler to optimize away the existence of the reference variable 'ri', and do the assignment directly to the appropriate array member. The compiler that I am using (Microsoft C/C++ 12/VS2003) generated the single 8086 assembly instruction for the assignment:

mov DWORD PTR _array$[esp+84], 4

No use of the variable 'ri', and it takes up no space. QED



Maybe with your compiler and on your system. On my system (I'm using PowerPC Linux natively running on a G4, compiling my code with gcc 4.1), the outcome is different. The code:

void testfunc1()
{
int array[10] = {0}; // simple array
int& ri = array[3]; // reference to array member
ri = 4; // change array member through reference
}

gets compiled into:

_Z9testfunc1v:
.LFB1489:
stwu 1,-80(1)
.LCFI6:
mflr 0
.LCFI7:
stw 31,76(1)
.LCFI8:
stw 0,84(1)
.LCFI9:
mr 31,1
.LCFI10:
addi 0,31,12
li 9,40
mr 3,0
li 4,0
mr 5,9
bl memset
addi 9,31,12
addi 0,9,12
stw 0,8(31)
lwz 9,8(31)
li 0,4
stw 0,0(9)
lwz 11,0(1)
lwz 0,4(11)
mtlr 0
lwz 31,-4(11)
mr 1,11
blr

The code:

void testfunc2()
{
int array[10] = {0}; // simple array
array[3] = 4;
}

gets compiled into:

_Z9testfunc2v:
.LFB1490:
stwu 1,-80(1)
.LCFI11:
mflr 0
.LCFI12:
stw 31,76(1)
.LCFI13:
stw 0,84(1)
.LCFI14:
mr 31,1
.LCFI15:
addi 0,31,8
li 9,40
mr 3,0
li 4,0
mr 5,9
bl memset
li 0,4
stw 0,20(31)
lwz 11,0(1)
lwz 0,4(11)
mtlr 0
lwz 31,-4(11)
mr 1,11
blr

The code:

void testfunc3()
{
int array[10] = {0}; // simple array
int *const rp = &array[3]; // pointer to array member
*rp = 4; // change array member through const pointer
}

gets compiled into:

_Z9testfunc3v:
.LFB1491:
stwu 1,-80(1)
.LCFI16:
mflr 0
.LCFI17:
stw 31,76(1)
.LCFI18:
stw 0,84(1)
.LCFI19:
mr 31,1
.LCFI20:
addi 0,31,12
li 9,40
mr 3,0
li 4,0
mr 5,9
bl memset
addi 9,31,12
addi 0,9,12
stw 0,8(31)
lwz 9,8(31)
li 0,4
stw 0,0(9)
lwz 11,0(1)
lwz 0,4(11)
mtlr 0
lwz 31,-4(11)
mr 1,11
blr

Now, Jeff, notice that the codes generated for testfunc1 and testfunc3 are the same. testfunc2, on the other hand, gets a compiled into a different set of instructions. QED (FOR GCC on PowerPC).

By the way, are you sure that your wonderful Microsoft compiler didn't simply optimize the reference variable away? Try my version of your code that uses a const pointer instead of a reference (in testfunc3) and see what code the compiler will produce. If it produces the same assembly code as before, please try to turn-off the optimizer and then see what happens.

I hope that Gatik will forgive me, if I interpret him that by saying that "many people think of a reference variable as an alias" he meant to say this:

Many people think that a declared&defined reference variable is interpreted by the compiler to be just another name for the original variable.

And that's as simple as that. Gatik then proceeded to say that the above notion is generally not true. What's your problem with that?

Gatik *does not say* that references are the same as const pointers. What he says is that they are the automatically dereferenced versions thereof. That's why in your code snippet:

jefito wrote:
double d;
double& rd = d;
cout << "size of d = " << sizeof d << " size of rd = " << sizeof rd << endl;


You get "8."

Another interesting example is taking the address of "rd." You will get the same number as that for "d."

That's why I view reference variable as const pointers with a twist. I don't know how the Microsoft compiler implements them, but in my case: if a reference variable doesn't occupy any space, that means that, if a corresponding const pointer is defined instead, it, too, will be optimized away.

I hope I didn't introduce any more confusion than is already there!! In fact, I also hope that I clarified some.

I do, however, agree with you on this: maybe the author should indeed be more precise, elaborate, and rigorous when explaining the relation between references and const pointers. It is a site that often gets visited by knowledgeable folks, after all.

Regards,
Ilya
GeneralRe: Confusing article Pin
jefito24-Mar-06 9:58
jefito24-Mar-06 9:58 
GeneralRe: Confusing article Pin
Ilya Lipovsky24-Mar-06 10:52
Ilya Lipovsky24-Mar-06 10:52 
GeneralRe: Confusing article Pin
Matthias Becker2-Apr-06 8:45
Matthias Becker2-Apr-06 8:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.