Operator Overloading newbie question

This is a discussion on Operator Overloading newbie question within the C++ Programming forums, part of the General Programming Boards category; In my C++ book, I don't understand this particular example demonstrating operator overloading: Code: ThreeD ThreeD :: operator=(ThreeD &op2) { ...

  1. #1
    Back after 2 years Panopticon's Avatar
    Join Date
    Dec 2002
    Posts
    262

    Operator Overloading newbie question

    In my C++ book, I don't understand this particular example demonstrating operator overloading:

    Code:
    ThreeD ThreeD :: operator=(ThreeD &op2) {
    x=op2.x;
    y=op2.y;
    z=op2.z;
    return *this;
    }
    What I don't understand is the need to return *this. I know the function is specified as returning an object type 'ThreeD' but isn't that redundant? Would the following achieve the same thing:

    Code:
    void ThreeD :: operator=(ThreeD&op2) {
    x=op2.x;
    y=op2.y;
    z=op2.z;
    return;
    }
    I AM WINNER!!!1!111oneoneomne

  2. #2
    Registered User
    Join Date
    Nov 2002
    Posts
    1,109
    no it would not, because it is designed to assign. the = is the assignment operator, so it needs to return a ThreeD object, not void. if it does return void, then there would be no point to the operator.
    basically, it will assign like this:
    Code:
    int main() {
    	ThreeD object1, object2;
    	
    	object1 = object2;
    	
    	return 0;
    }
    returning *this and having the function return a ThreeD object allows you to do this in main.

  3. #3
    Back after 2 years Panopticon's Avatar
    Join Date
    Dec 2002
    Posts
    262
    Ok thanks for your help. I tried it with void and it behaved as predicted. I think the reason why the book used *this was to allow compound assignments like a=b=c=d; to occur.
    I AM WINNER!!!1!111oneoneomne

  4. #4
    Registered User
    Join Date
    Nov 2002
    Posts
    1,109
    okay. thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Stupid Newbie question
    By TimL in forum C++ Programming
    Replies: 4
    Last Post: 07-22-2008, 05:43 AM
  2. C prog newbie question
    By Draginzuzu in forum C Programming
    Replies: 1
    Last Post: 02-03-2003, 06:45 PM
  3. a stupid question from a newbie
    By newcomer in forum C++ Programming
    Replies: 4
    Last Post: 01-11-2003, 04:38 PM
  4. confusion with integers (newbie question)
    By imortal in forum C Programming
    Replies: 7
    Last Post: 12-06-2002, 04:09 PM
  5. newbie class templates question
    By daysleeper in forum C++ Programming
    Replies: 2
    Last Post: 09-18-2001, 10:50 AM

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