On Jan 9, 2008 9:32 PM, onecrazeemom <[EMAIL PROTECTED]> wrote:

> Hello all. I am just a beginning programmer. I have started taking a
> C++ home study course. I am able, mostly, to understand what I have
> done so far. But now I am working on pointers and references... and I
> am a little confused. What is the point of a reference if a pointer
> seems to do the same thing?

Syntactically, references are a lot cleaner when passed as arguments
into a function or method (pass-by-reference).

-- using pointers (C-style pass by reference)

void some_function(int *x, int *y);

int x, y;

some_function(&x, &y);

-- using references (C++ style pass by reference)

void some_function(int & x, int & y);

int x, y;

some_function(x, y);

However, references can't be dereferenced like a pointer can ... a
reference is more like an alias for an already existing variable. You
also can't have a reference to NULL, but you can have a NULL pointer.

For referenced objects, you use the . when using members, instead of
->, as below:

MyObj obj;
MyObj *newObj = new MyObj; //dynamically allocated memory, you have to
delete when done
MyObj & anotherObj = obj; //anotherObj is a reference to obj, changing
anotherObj changes obj, no deleting necessary!

obj.method()1;
newObj->method1();
anotherObj.method1(); //same as calling obj.method1();

When you get to studying operator= and copy constructors in C++, you
will see where references are used quite a bit

-- Brett
------------------------------------------------------------
"In the rhythm of music a secret is hidden;
    If I were to divulge it, it would overturn the world."
               -- Jelaleddin Rumi

Reply via email to