Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ difference between reference, objects and pointers

This is a question from an exam in an advanced course in OOP, taught in C++ (in TAU university, this semester):

Q: What is the difference between a C++ pointer and a reference?

A.  A reference is the entire object while a pointer is only the address of it.
B.  The same meaning, and difference is only in syntax and usage.
C.  The syntax used to access the object.
D.  Pointers are simple address to the object while a reference uses the virtual table.

Which is the correct answer?

The course teacher claims that A is the correct one, and that a reference to an object is, in fact, the object itself. Is that correct? I realize that accessing the reference is equivalent to accessing the object itself, however, when destructing a reference, we do not destruct the object itself. A reference is an alternative name for the object, but saying that reference==object true?

BTW, the lecturer gave the following link to an faq as support for his claim, a quote:

"Important note: Even though a reference is often implemented using an address in the underlying assembly language, please do not think of a reference as a funny looking pointer to an object. A reference is the object. It is not a pointer to the object, nor a copy of the object. It is the object."

But still, I believe this is incorrect.

like image 842
amitlicht Avatar asked Jul 11 '10 18:07

amitlicht


People also ask

What is the difference between references and pointers?

Pointers: A pointer is a variable that holds the memory address of another variable. A pointer needs to be dereferenced with the * operator to access the memory location it points to. References: A reference variable is an alias, that is, another name for an already existing variable.

Is an object reference a pointer?

References are not a kind of pointer. They are a new name for an existing object.

Are references pointers?

A pointer in C++ is a variable that holds the memory address of another variable. A reference is an alias for an already existing variable. Once a reference is initialized to a variable, it cannot be changed to refer to another variable. Hence, a reference is similar to a const pointer.


1 Answers

They're all wrong.

A reference is essentially a synonym for another object. Internally, it is often implemented as a pointer, but it has the syntax as if it were the object it refers to.

A pointer is a separate object that stores the memory address of the object it points to (or 0 if it doesn't point to an object).

You could say that the reference is the object that it refers to (it certainly acts that way), but it is not. If a reference goes out of scope then the object it refers to is not destructed, so the reference is not the object.

like image 97
Peter Alexander Avatar answered Sep 29 '22 15:09

Peter Alexander