Learning  C++
Home
Tutorials
C++  Programs
Contact  us
Sitemap
Your Ad Here
Your Ad Here
Operator  Overloading  with  member  function  or  friend

We  have  three  distinct  ways ( styles )  of  overloading.


1 )  Object + Object


For  Example,
Complex  operator  +  ( Complex  b ) ;


It  will  imply  that  you  are  adding  two  objects  of  class  Complex  and  the  result  is  also of class  Complex.


C = A + B ;  //  A object  invokes  operator + ( )  function


2  )  Object  +  basic  data  type  ( say  int )


For  Example,
classA  operator  +  ( int  m ) ;


This  poses  no  problem.
C = A + 15 ;  //  A object  invokes  operator + ( )  function


3  )  Basic  data  type  +  Object


This  poses  problem  as  basic  data  type  is  not  a  class.  
C = 15 + A ;  //  15  cannot  invoke  operator + ( )  function


The  solution  is  to  use  a  friend  function.


A  declaration  will  take  the  form:


friend  classA  operator  +  ( int  m,  classA  a ) ;
C = 15 + A ;  //  ok   friend  function  takes  all  arguments  explicitly