Operator Overloading (=)

This is a discussion on Operator Overloading (=) within the C++ Programming forums, part of the General Programming Boards category; foo& operator= (const foo& f) { var1 = f.var1, var2 = f.var2; return *this; } foo foo1; foo foo2; //... ...

  1. #1
    mikeadi
    Guest

    Operator Overloading (=)

    foo& operator= (const foo& f) {

    var1 = f.var1, var2 = f.var2;

    return *this;
    }


    foo foo1;
    foo foo2;

    //...

    foo2 = foo1;
    ok...
    the this pointer in this class points to the object on the left (foo2), the object that is calling this function (the op overload func, =). so why do i have to return *this?

    if this (foo2) calls the function, shouldnt it know whats intended?

    am i missing something?

  2. #2
    Programming Sex-God Polymorphic OOP's Avatar
    Join Date
    Nov 2002
    Posts
    1,078
    you return *this so that you can do

    foo1 = foo2 = foo3;

    You can string things together, or you can use the object for something else!

  3. #3
    mikeadi
    Guest

    1 more thing

    ok, one more thing.

    a constructor cant return anything. keep that in mind.

    class foo
    {
    public:
    foo() {}
    foo(const &foo) : var1(foo.var1), var2(foo.var2) {}
    private:
    int var1;
    int var2;
    };

    and its smart enough to know whats implied, that the object calling it is going to get the value thats intended.

    ok wait thats kinda similar, but not entirely.. : )

  4. #4
    mikeadi
    Guest

    oooh

    oh i understand now! thanks

  5. #5
    Programming Sex-God Polymorphic OOP's Avatar
    Join Date
    Nov 2002
    Posts
    1,078

    Re: 1 more thing

    Originally posted by mikeadi
    a constructor cant return anything. keep that in mind.
    Actually, you can think of a constructor as "automagically" returning a reference to an object. That's why you can do things like

    void Function( Player& );

    Function( Player() );

    And have it work.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21