OOP Experiment No 1-1
OOP Experiment No 1-1
Experiment No 1
Title: Implement a class Complex which represents the Complex Number data type. Implement the
following
1. Constructor (including a default constructor which creates the complex number 0+0i).
2. Overload operator+ to add two complex numbers.
3. Overload operator* to multiply two complex numbers.
4. Overload operators << and >> to print and read Complex Numbers.
Theory:
Operator Overloading
Operator overloading is a feature in C++ that enables operators (such as +, -, etc.) to work
with user-defined data types. This mechanism is known as compile-time polymorphism and
provides the advantage of customizing operator behavior for different data types.
For example, we can overload "+" operator to perform addition on integers, concatenation on
strings, and addition on complex numbers. This enhances the versatility of operators,
allowing them to operate on awider range of data types.
class ClassName
{
...
public
ReturnType operator OperatorSymbool(argument list)
{
// Implementation logic
}
... }
1. In the case of a non-static member function, the binary operator should have only one
argument and the unary should not have an argument.
2. In the case of a friend function, the binary operator should have only two arguments and the
unary should have only one argument.
3. Operators that cannot be overloaded are .* :: ?:
4. Operators that cannot be overloaded when declaring that function as friend function are = () [] -
>.
5. The operator function must be either a non-static (member function), global free function or a
friend function.
FAQs