In C++, stream insertion operator “<<” is used for output and extraction operator “>>” is used for input.
We must know following things before we start overloading these operators.
1) cout is an object of ostream class and cin is an object istream class
2) These operators must be overloaded as a global function. And if we want to allow them to access private data members of class, we must make them friend.
Why these operators must be overloaded as global?
In operator overloading, if an operator is overloaded as member, then it must be a member of the object on left side of the operator. For example, consider the statement “ob1 + ob2” (let ob1 and ob2 be objects of two different classes). To make this statement compile, we must overload ‘+’ in class of ‘ob1’ or make ‘+’ a global function.
The operators ‘<<' and '>>' are called like 'cout << ob1' and 'cin >> ob1'. So if we want to make them a member method, then they must be made members of ostream and istream classes, which is not a good option most of the time. Therefore, these operators are overloaded as global functions with two parameters, cout and object of user defined class.
Following is complete C++ program to demonstrate overloading of <> operators.
Enter Real Part 10 Enter Imaginary Part 20 The complex object is 10+i20
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Rules for operator overloading
- Function overloading and return type
- Function overloading and const keyword
- Does overloading work with Inheritance?
- Function Overloading and float in C++
- Function Overloading in C++
- Operator Overloading in C++
- Overloading Subscript or array index operator  in C++
- C++ | Operator Overloading | Question 10
- Constructor Overloading in C++
- Namespaces in C++ | Set 4 (Overloading, and Exchange of Data in different Namespaces)
- Function Overloading vs Function Overriding in C++
- Overloading New and Delete operator in c++
- C++ Program to concatenate two strings using Operator Overloading
- Operator overloading in C++ to print contents of vector, map, pair, ..
- Types of Operator Overloading in C++
- Increment (++) and Decrement (--) operator overloading in C++
- C++ program to compare two Strings using Operator Overloading
- Operator Overloading '<<' and '>>' operator in a linked list class
- Count number of Unique Triangles using Operator overloading
Improved By : jacksonthall22