Friday 17 February 2023

Operator Overloading

 

Unit 3: Operator Overloading (12)     


3.1  Concept of Operator Overloading

3.2  Defining Operator Overloading

3.3     Rules of Operating Overloading

3.4     Unary Operator Overloading

3.5     Return types in overloading function

3.6     Binary Operator Overloading

3.7     Manipulation String using Operator Overloading

3.8     New and Delete Operator Overloading

3.9     Data Conversion

 

Practical Works:

·       Create unary operator overloading. 

·       Apply different types of operator overloading function return methods.

·       Apply binary operator overloading

·       Create Data conversion methods

 

 

1.    Concept of Operator Overloading/Defining Operator Overloading

a.      An operator overloading is defined using a special function called operator function, which describes the task to be done by the operator.

b.     The syntax for operator function is:

 

return_type operator existing_operator (arguments);

where operator is keyword and existing_operator is any valid operator to be overloaded. Thus, Operator existing_operator is name of the operator function.

c.      Operator function may be either member function or friend function of class.

d.     The number of arguments for operator function depends on type of operator either it is unary or binary and type of function either it is member function or friend function.

 

2.    Rules of Operating Overloading

In C++, following are the general rules for operator overloading.

1) Only built-in operators (i.e. predefined operators in the C++) can be overloaded. New operators ( such as $, @, **) can not be created.
2)
Arity of the operators  ( the number of operands an operator can take for example unary binary and ternery) cannot be changed.
3) Precedence and associativity of the operators cannot be changed.
4) The overloaded operator must have at least one user-defined type operand


5) friend function cant be used to overload operators Assignment (=), subscript ([]), function call (“()”), and member selection (->) operators.
6) Except the operators specified in point 6, all other operators can be either member functions or a non member functions.
7 ) Some operators like (assignment)=, (address)& and comma (,) are by default overloaded.

 

a.     Unary Operator Overloading/ What is operator overloading? Describe overloading unary operator with example.

The operator that requires only one operand to perform its operation is known as unary operator. For example: unary minus (-), unary plus (+), increment (++), decrement—, logical not (!), pointer indirection or dereferences (*) and address of ( &).

The operator function declared as member function can be used with following syntax.

Return_type operator unary_operator ()

        {
                Body;
             
        }

Example: write a program to overload a unary minus operator (i.e. -).

 

#include <iostream>
using namespace std;
 
class complex {
      int real, image;             
           
   public:
      // required constructors
      complex(int r, int i) {
         real = r;
         image = i;
      }
      complex() {
         real = 0;
         img = 0;
      }
      
      
      // overloaded minus (-) operator
      void operator- () {
         real = -real;
         img = -image;
         
      }
      // method to display complex
      void display() {
         cout << "Real Part: " << real <<endl;
         cout << "Imaginary Part: " << img <<endl;
      }
 
};
 
Void main() {
   Complex comp(-7, 3);
   cout << "the complex number is: "<<endl;
   comp.Display();
   -comp; //same as comp.operator –()
   cout << endl<<”the complex number after unary minus:”<<endl;
   comp.Display();
}
 

Output

The complex number is :

Real Part:4

Imaginary part:5

The complex number after unary minus:

Real Part:-4

Imaginary Part:-5

Example: example explain how minus (-) operator can be overloaded for prefix as well as postfix usage.

#include <iostream>
using namespace std;
 
class Distance {
   private:
      int feet;             // 0 to infinite
      int inches;           // 0 to 12
      
   public:
      // required constructors
      Distance() {
         feet = 0;
         inches = 0;
      }
      Distance(int f, int i) {
         et = f;
         incfehes = i;
      }
      
      // method to display distance
      void displayDistance() {
         cout << "F: " << feet << " I:" << inches <<endl;
      }
      
      // overloaded minus (-) operator
      Distance operator- () {
         feet = -feet;
         inches = -inches;
         return Distance(feet, inches);
      }
};
 
int main() {
   Distance D1(11, 10), D2(-5, 11);
 
   -D1;                     // apply negation
   D1.displayDistance();    // display D1
 
   -D2;                     // apply negation
   D2.displayDistance();    // display D2
 
   return 0;
}

When the above code is compiled and executed, it produces the following result −

F: -11 I:-10
F: 5 I:-11

 

 

b.    Return types in overloading function

When multiple definitions for the same function name in the same scope and the definition of the function must differ from each other by the types and/or the number of arguments in the argument list is known as return types in overloading function. You cannot overload function declarations that differ only by return type.

The function overloading is basically the compile time polymorphism. It checks the function signature. If the signatures are not same, then they can be overloaded. The return type of a function does not create any effect on function overloading. Same function signature with different return type will not be overloaded.

Following is the example where same function print() is being used to print different data types

#include <iostream>
using namespace std;
class printData {
   public:
      void print(int i) {
         cout << "Printing int: " << i << endl;
      }
      void print(double f) {
         cout << "Printing float: " << f << endl;
      }
      void print(char* c) {
         cout << "Printing character: " << c << endl;
      }
};
int main(void) {
   printData pd;
   pd.print(5); // Call print to print integer
   pd.print(500.263); // Call print to print float
   pd.print("Hello C++"); // Call print to print character
   return 0;
}

Output

Printing int: 5
Printing float: 500.263
Printing character: Hello C++

 

c.     Binary Operator Overloading

The operator which require two operands for its operation is known as binary operators. For example: binary plus (  +), binary (  -), multiplication (*), division ( /), greater than ( >), less than (<), equality operator (= =) etc. the member function can be used as operator function using syntax

Return_type operator binary_operator (object2_of_class)

        {
                Body;
             
        }
 

Example: write a program to overload a binary plus operator (+) for addition of two complex number.

 

#include <iostream>
using namespace std;
 
class complex {
   private:
      float real, image;             
           
   public:
      // required constructors
      complex() {
         real = 0;
         image = 0;
      }
      complex(float r, float i) {
         real = r;
         img = i;
      }
      
      
      // overloaded binary plus operator +
      Complex operator + (complex c) {
         Complex temp;
         temp.real=real+c.real;
         temp.img=img+c.img;
         return (temp);
                  
      }
      // method to display complex
      void display() {
         cout << real<<”+j”<<img<<endl;
         
      }
 
};
 
Void main() {
   Complex c1 (2, 5),c2 (4, 6), c3;
   C3=c1+c2; //equivalent to c1.operator+(c2)
   Cout<<”c1=”,c1.display();
   Cout<<”c2=”,c2.display();
   Cout<<”c3=”,c3.display();
   
  }
 

Output

C1=2 +j 5

C2=4 +j 6

C3=6 +j 11

 

 

d.     Manipulation String using Operator Overloading

e.      New and Delete Operator Overloading

f.      Data Conversion

 

No comments:

Post a Comment