reference vs object handle

T

terminator800tlgm

I don't understand the difference between ojbect handle and reference.
For example,

class Stack
{
private:
CD cd_obj; // cd object
DVD & dvd_ref;// dvd reference

Why is it that dvd_ref can ONLY be initialized in the Stack's
constructor whereas cd_obj can be initialized during the Stack
object's lifetime?

Also, why is not allowed to return by reference a locally created
object?
For example,


Vector Vector::eek:perator+(const Vector & b) const
{
return Vector(x+b.x, y+b.y); //Why is this allowed?

}

Vector & Vector::eek:perator+(const Vector & b) const
{
return Vector(x+b.x, y+b.y); //Why is this NOT allowed?

}
 
C

Cy Edmunds

I don't understand the difference between ojbect handle and reference.
For example,

class Stack
{
private:
CD cd_obj; // cd object
DVD & dvd_ref;// dvd reference

Why is it that dvd_ref can ONLY be initialized in the Stack's
constructor whereas cd_obj can be initialized during the Stack
object's lifetime?

A reference must be initialized. For instance you can't write:

int &foo;

You would have a reference to nothing in particular which is not allowed.
Actually this is a big advantage of references over pointers which can be
left uninitialized.

If dvd_ref isn't initialized in Stack's constructor it would violate this
rule.
Also, why is not allowed to return by reference a locally created
object?
For example,


Vector Vector::eek:perator+(const Vector & b) const
{
return Vector(x+b.x, y+b.y); //Why is this allowed?

Consider the calling sequence:

Vector v = v1 + v2;

Effectively this is the same as

Vector v = Vector(v1.x + v2.x, v1.y + v2.y);

No problem here. The values of the temporary on the right hand side are
copied to the values in v. (Conceptually at least -- the compiler may
optimize that out.)
}

Vector & Vector::eek:perator+(const Vector & b) const
{
return Vector(x+b.x, y+b.y); //Why is this NOT allowed?

Again, consider the calling sequence:

Vector &v = v1 + v2;

which is now the same as the nonsense statement

Vector &v = Vector(v1.x + v2.x, v1.y + v2.y);

Since the right hand side is a temporary object it can hardly be used to
create a valid reference.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,050
Latest member
AngelS122

Latest Threads

Top