<terminator800tlgm@hotmail.com> wrote in message
news:413685a6.0310311456.7f7567e5@posting.google.c om...[color=blue]
> 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?[/color]
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.
[color=blue]
>
> Also, why is not allowed to return by reference a locally created
> object?
> For example,
>
>
> Vector Vector::operator+(const Vector & b) const
> {
> return Vector(x+b.x, y+b.y); //Why is this allowed?[/color]
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.)
[color=blue]
>
> }
>
> Vector & Vector::operator+(const Vector & b) const
> {
> return Vector(x+b.x, y+b.y); //Why is this NOT allowed?[/color]
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.
[color=blue]
>
> }[/color]
--
Cy
http://home.rochester.rr.com/cyhome/