Friday, March 26, 2010

Operator overloading

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   
// overloaded subscript operator for non-const Arrays;
87   // reference return creates a modifiable lvalue
88   int &Array::operator[]( int subscript )
89   {
90      // check for subscript out-of-range error
91      if ( subscript < 0 || subscript >= size )
92      {
93         cerr << "\nError: Subscript " << subscript
94            << " out of range" << endl;
95         exit( 1 ); // terminate program; subscript out of range
96      } // end if
97
98      return ptr[ subscript ]; // reference return
99   } // end function operator[]
100
101  // overloaded subscript operator for const Arrays
102  // const reference return creates an rvalue
103  int Array::operator[]( int subscript ) const
104  {
105     // check for subscript out-of-range error
106     if ( subscript < 0 || subscript >= size )
107     {
108        cerr << "\nError: Subscript " << subscript
109           << " out of range" << endl;
110        exit( 1 ); // terminate program; subscript out of range
111     } // end if
112
113     return ptr[ subscript ]; // returns copy of this element
114  } // end function operator[]
 
 
 
LINK :http://www.deitel.com/articles/cplusplus_tutorials/20060204/cplusplus_operatoroverloading_arrayclass_Page3.html 

2 comments:

Followers