Operator Function must be member Function or at least take one argument of uesr defined type
To overload operator we have three options .
1)
Member Functions : when left hand Operand is of Class type
obj + 2 ; obj1 + obj2 .
This will not work for 3 + obj1
as it will become 3.operator+(obj1) and + is not overloaded for int type.
Any operator function intended to accept first operand as basic type CAN'T be Member function.
Imp :
operator = , [] , -> , () ,->* all these must be Member
2)
Global Functions : If we want left hand operand to be of other class type .
Example: >> , << . To support 4 + obj1
3)
Friend functions : friend is just provided for global functions to get access
of Private and protected members .
But if we dont have Constructor number(int I = 0) which is imlicitly casting
1 ----> number And letting a + 1; to work.
compilation will fail .
BJARNE recommendation:
1.Operator that inherently modify value of first Argument should be member fuction. like +=,-= ,*= and all .
complex & operator+=(complex a) ;
2. Operator that simply produce a new value based on its Arguments as + ,- ,*, / should defined outside of class.
complex operator + (const complex & a , const complex & b)
{ complex r = a;
return r+=b;
}
Q Why cant we overload :: (Scope ) . (dot ) and .* (member selection throgh ptr to functoion) ?
Ans:
All of these operator take second argument as name not as value .
They are used to refer members not to operate on them.
Q Why -> is overloadable and .(dot is not )?
--------------overloading array ---------
86
87
88 int &Array::operator[]( int subscript )
89 {
90
91 if ( subscript < 0 || subscript >= size )
92 {
93 cerr << "\nError: Subscript " << subscript
94 << " out of range" << endl;
95 exit( 1 );
96 }
97
98 return ptr[ subscript ];
99 }
100
101
102
103 int Array::operator[]( int subscript ) const
104 {
105
106 if ( subscript < 0 || subscript >= size )
107 {
108 cerr << "\nError: Subscript " << subscript
109 << " out of range" << endl;
110 exit( 1 );
111 }
112
113 return ptr[ subscript ];
114 }