operator overloading

Assignment "=" operator overloading

Page 1 of 1

1 Replies - 842 Views - Last Post: 10 October 2010 - 05:07 AM Rate Topic: -----

#1 rejah  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 14-March 08

operator overloading

Posted 10 October 2010 - 04:41 AM

Hi all,
I have written the following code for operator overloading for my class called board.

Note that there is no return statement.

board& board::  operator=(const board& rhs)
    {
		for(int i =0; i< 5; i++)
			for(int j=0; j < 5;j++ )
			{
				squares[i][j].value = rhs.squares[i][j].value;
				squares[i][j].piece = rhs.squares[i][j].piece;
			}
		asterScore = rhs.asterScore;
		dollarScore = rhs.dollarScore;
		
	}



Also I have used it in the main() as follows

board1 = *tempBoard;     //where tempBoard is board* and board1 is board type.




The code works (to my surprise!) . I wonder why the compiler did not give me a return statement error. And could someone please advice on the proper way of using the operator overloading function? (above code modified?).


Thanks in advance.

Is This A Good Question/Topic? 0
  • +

Replies To: operator overloading

#2 Munawwar  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 162
  • View blog
  • Posts: 457
  • Joined: 20-January 10

Re: operator overloading

Posted 10 October 2010 - 05:07 AM

It's undefined, you shouldn't be doing it.
This code...
class test {
    public:
    int value;
    test() {
        value=-1;
    }
    test(int v) {
        value=v;
    }
    test& operator=(test& t) {
        cout<<t.value<<endl;
    }
};
int main(void) {
    test a(0),b(1),c(2);
    c=(a=B)/>;

   return 0;
}


...gave me result:
1
4673452



EDIT:
So why don't you keep the return type as void...or if you still want to return board& type then do this:
board& board::  operator=(const board& rhs)
    {
		for(int i =0; i< 5; i++)
			for(int j=0; j < 5;j++ )
			{
				squares[i][j].value = rhs.squares[i][j].value;
				squares[i][j].piece = rhs.squares[i][j].piece;
			}
		asterScore = rhs.asterScore;
		dollarScore = rhs.dollarScore;

	        return *this;	//Return the object pointed by 'this'
	}


This post has been edited by Munawwar: 10 October 2010 - 05:11 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1