Tuesday, March 4, 2008

Reference in C++

It is abruptly that I want to write about C++. Although I have written a little about ASP.Net 2.0, I am not in expertise to make comparation between native C++ and .Net language. It's just another session of my writing time. I would like to write about reference.

First, let us see this code in C++
int Value = 0;
int &RefValue = Value;

The code above is a declaration of a reference. The declaration use & operator. It means RefValue is an alias for Value. RefValue and Value refer to the same memory location. How we use reference?

Let's go on.
In the above code, both Value and RefValue has the same value, namely 0. If we add the code with :

RefValue = 1; //both Value and RefValue are equal to 1.
++Value; //Value and RefValue are equal to 2.

You could think in mind, what about pointer. Pointer is different with reference, it refers to a memory location that contain address of the target memory location. Let's see this :

int Value = 0;
int &RefValue = Value;
int *PtrValue = &Value;

Pointer PtrValue is declared using * operator.
That's it.

No comments: