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.
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 "ref" is really just an
// address, it dereferences itself, so this
// line is equivalent to "cout << x"
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.