reference vs object handle

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • terminator800tlgm@hotmail.com

    reference vs object handle

    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::operato r+(const Vector & b) const
    {
    return Vector(x+b.x, y+b.y); //Why is this allowed?

    }

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

    }
  • Cy Edmunds

    #2
    Re: reference vs object handle

    <terminator800t lgm@hotmail.com > wrote in message
    news:413685a6.0 310311456.7f756 7e5@posting.goo gle.com...[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::operato r+(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::operato r+(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



    Comment

    Working...