Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Problem in Understanding of Object references ??????

Status
Not open for further replies.

isaisa

Programmer
May 14, 2002
97
IN
Hi,
I am a beginner in C++ programming. I am not able to understand the difference between a pointer to a class object and reference to an object.
How C++ compiler treats reference different from pointer to an object. Please hepl.

Thanks
Sanjay
 
Assuming you know how a pointer works, a reference is essentially a pointer with the following differences:

1) it is constant (i.e. it always points, or refers, to the same object)

2) it must be initialized when it is declared, and it automatically takes the address of the variable it is initialized to.

Code:
// e.g.
int x;
int &ref = x;    // "ref" is assigned the ADDRESS of "x"

3) whenever it appears in your code, it automatically dereferences itself.

Code:
// e.g.
int x = 5;
int &ref = x;
cout << ref;    // here, even though &quot;ref&quot; is really just an
                // address, it dereferences itself, so this
                // line is equivalent to &quot;cout << x&quot;
 
Hi chipperMDW,

Thanks a lot for your help. I was not aware of the dereferencing part of it [point no 3 as you mentioned].

Thanks,
Sanjay
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top