write a program to demonstrate operator overloading in c++?

vijaya shankar.k | 500 Views | c++ | 11 Aug 2016

 

Operator Overloading :

  • Operator overloading is an important concept in C++.
  • The term of operator is defined as ad hoc polymorphism, is a specific case of polymorphism.
  • When an operator is overloaded with user define argument and it performs operation on user-defined data type.
  • In  C++  use the keyword “operator” for overloading of operators.

Example :

Consider variables a, b, c of some user-defined type, such as matrices:

a + b * c

In C++ language that supports operator overloading, and with the usual assumption that the '*' operator has higher precedence than '+' operator, this is a concise way of writing:

add (a, multiply (b,c))

Syntax :

operator([parameters])
{
  Statements
}

Cannot Overloading the following operator in C++:

sizeof

Object size information

typeid

Object type information

::

Used to resolve the scope of variable or function of a class

? :

Ternary Operator (conditional operator)

. (dot)

Dereferencing Operator.

.*

Member selection with pointer to
member

Algorithm :

Step 1: Start the program.

Step 2: Declare the class.

Step 3: Declare the variables and its member function.

Step 4: Using the function getvalue() to get the two numbers.

Step 5: Define the function operator +() to add two complex numbers.

Step 6: Define the display function.

Step 7: Declare the class objects c1,c2 and c3.

Step 8: Call the function getvalue using c1 and c2.

Step 9: Calculate the value for the object result by calling the function operator + .

Step 10: Call the display function using c1 and c2 and c3.

Step 11 : Then check the imaginary value.

Step 12: Return the values.

Step 13: Stop the program.

Sample Code :

#include<iostream.h>
#include<conio.h>
class complex   //Class Declaration
{
 float
 real, imaginary;  //Data Member Declaration
 public: complex()  //Default Constructor to initialize data member
 {
  real=0;
  imaginary=0;
 };
 complex operator + (complex c2)  //Overloading + operator to add two complex number
 {
  complex t;
  t.real=real+c2.real;
  t.imaginary=imaginary+c2.imaginary;
  return t;
 }
 void getvalue()  //Function to get complex number value
 {
  cout<<"\n Enter the Real value:\t";
  cin>>real;
  cout<<"\n Enter the Imaginary value:";
  cin>>imaginary;
 }
 void display()  //Function to display complex number value
 {
   cout<<"\t"<<real;
   if(imaginary>=0)
   {
     cout<<"+";
   }
  cout<<imaginary<<"i"<<endl;
  }
};
int main()
{
 clrscr();
 complex  c1,c2,c3;  //Object declaration
 cout<<"\n\t\t\t Operator Overloading \n";
 cout<<endl<<"\n The value of first object\t";
 c1.getvalue();
 cout<<endl<<"\n The value of Second object\t";
 c2.getvalue();
 cout<<endl<<"\n The Sum is ";
 c3=c1+c2;  //Call overloaded operator to add complex number
 c3.display();
 getch();
 return(0);
}

Sample Output :