Operator Overloading Clarification

what is the best and most efficient way to overload these operators.
Every website i go to does it differently and i'm confused about all the "const" that is used.
I know you can overload these operators to do anything but i'm trying to build a class with these empty functions so i don't have to retype the function decelerations every time, but instead just fill them with code.

this is what i've made so far and i'm not sure if i'm going to run into problems later because of the consts.. or accidently change something that shouldn't change because of a lack of consts.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
		const T   operator + (const  T & addedNumber)      const;	
		const T   operator - (const  T & subtractedNumber) const;		
		const T   operator * (const  T & multipliedNumber) const;
		const T   operator / (const  T & dividedNumber)    const;
		
		const T & operator = (const  T & number);
		const T & operator +=(const  T & number);
		const T & operator -=(const  T & number);
		const T & operator *=(const  T & number);
		const T & operator /=(const  T & number);
		
		bool operator == (const T & comparedNumber) const;
		bool operator != (const T & comparedNumber) const;
		bool operator <  (const T & comparedNumber) const;
		bool operator >  (const T & comparedNumber) const;
		bool operator <= (const T & comparedNumber) const;
		bool operator >= (const T & comparedNumber) const;


do i need const in front of the "bool"s?
why do i get errors when i place a "const" after +=, -=, *=, etc.
just so confusing..
You definitely want all the parameters to be const, because passing by const reference is efficient.

Think about why you can't put const after the =, +=, -=, etc. operators. Putting it there would mean that the invoking object cannot be changed. Since the whole point of the "="s operation is to set the invoking object equal to something else, making it const would make no sense and is not allowed. Putting the const before the rest of the prototype is fine in this case though, because you do not want to be changing the result that is returned by reference.

For the +, -, *, and / operators, you definitely want the const at the end of prototype, so that the invoking object cannot be changed. This follows standard mathematic semantics; you don't want to be changing the y in x = y + z. As for the const at the beginning of the prototype, I'm not entirely certain, but I think that that is fine.

For the comparison operators, the const at the end is correct, and I suppose you could make them all return const by putting const at the beginning, but I don't really think that there's much reason to.

Is that clearer now?
Topic archived. No new replies allowed.