Pages

Sunday, 24 August 2014

Operator Overloading and Type Conversions

Operator Overloading and Type Conversions
We cannot change its syntax and its original meaning.
operator op is the function name.
member function x.operator op (y) ;    A=B+2 ; legal but A=2+B ; illegal (as the left hand operand is responsible for invoking the member function)
friend function operator op (x,y);  A=2+B; illegal
Example: Overloading >>

Rules of operator overloading:



Type Conversions
  • From basic to class
  • From class to basic
  • From one class type to another
From basic to Class type: By the use of constructors (it takes a single argument whose type is to be converted).
Char * str “hi”;
Myclass ob ;
ob=str; implicitly calls the costructor

From class to basic Type: we have to use a conversion function or a casting conversion function.
The casting conversion function must be class member with no arguments and must not specify any return type.
One class to another class type
Can be done either by a constructor or by a conversion function (Complier will treat in same way).
If constructor is used then the single argument will be the source class, which will be passed to the destination class for conversion.  
If conversion function (defined in the source class, and conversion also in source class) is used then the typename will refer to the destination class.
Summary of Type Conversions.

No comments:

Post a Comment