4
Reply

What is operator overloading? On which situation we will use this?

    Operator overloading is a concept to implement the same functionality for user define object (class instance)

    Operator overloading permits user-defined operator implementations to be specified for operations where one or both of the operands are of a user-defined class or struct type.

    Example

    using System;

    public struct Complex
    {
       public int real;
       public int imaginary;

       public Complex(int real, int imaginary)
       {
          this.real = real;
          this.imaginary = imaginary;
       }

       // Declare which operator to overload (+), the types
       // that can be added (two Complex objects), and the
       // return type (Complex):
       public static Complex operator +(Complex c1, Complex c2)
       {
          return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
       }
       // Override the ToString method to display an complex number in the suitable format:
       public override string ToString()
       {
          return(String.Format("{0} + {1}i", real, imaginary));
       }

       public static void Main()
       {
          Complex num1 = new Complex(2,3);
          Complex num2 = new Complex(3,4);

          // Add two Complex objects (num1 and num2) through the
          // overloaded plus operator:
          Complex sum = num1 + num2;

         // Print the numbers and the sum using the overriden ToString method:
          Console.WriteLine("First complex number:  {0}",num1);
          Console.WriteLine("Second complex number: {0}",num2);
          Console.WriteLine("The sum of the two numbers: {0}",sum);

       }
    }

    OUTPUT

    First complex number:  2 + 3i
    Second complex number: 3 + 4i
    The sum of the two numbers: 5 + 7i

    operator overloading is a concept of extending functionality of exixting operator.for instance take '+' operator.with this operator u can add two integers or u can concatenate two strings.these r the two built in functionalities of '+' operator.other than this two if u want to provide some more functionality to '+' u can achieve with operator overloading.

    This is called polymorphism in OOP's . we have constructor overloading,Function overloading, and Opertator overloading.

    The Operator overloading is we use '+' sign for Adding two numbers.The same '+'operator can be used to concatenate the strings.

    Exam:

    int a,b,c;string s1="Hello";

    string s2="World";

    String con;

    c=a+b;

    con=s1+s2;

    here is + sign is used for addition and concatenation.

    simple concept of polymorphism is same person acting differently in different places.