Design a C++ Class "Complex" with data members for real and imaginary part. Provide default and parameterized constructors. Write a program to perform arithmetic operations on two complex numbers using operator overloading (using either member functions or friend functions).

Operator Overloading:
It is a specific case of polymorphism where different operators have different implementations depending on their arguments. In C++ the overloading principle applies not only to functions but to operators too. That is, of operators can be extended to work not just with built-in types but also classes. A programmer can provide his or her own operator to a class by overloading the built-in operator to perform some specific computation when the operator is used on objects of that class.

An Example of Operator Overloading 
Complex a(1.2,1.3); //this class is used to represent complex numbers 
Complex b(2.1,3); //notice the construction taking 2 parameters for the real and imaginary part 
Complex c = a+b; //for this to work the addition operator must be overloaded

Arithmetic Operators Arithmetic Operators are used to doing basic arithmetic operations like addition, subtraction, multiplication, division, and modulus.
Overloadable operators:
+ - * / = < > += -= *= /= 
<< >> <<= >>= == != <= >= 
++ -- % & ^ ! | ~ &= ^= |= 
&& || %= []

1. To overload an operator in order to use it with classes we declare operator functions, which are regular functions whose names are the operator keyword followed by the operator sign that we want to overload. The format is:
2. type operator operator-symbol (parameters) {/*...*/ }
3. The operator keyword declares a function specifying what operator-symbol means when applied to instances of a class. This gives the operator more than one meaning, or "overloads" it. The compiler distinguishes between the different meanings of an operator by examining the types of its operands.

Mukesh Rajput
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment: