Which of the following operators should be preferred to overload as a global function rather than a member method?
(A) Postfix ++
(B) Comparison Operator
(C) Insertion Operator <<
(D) Prefix++
Answer: (C)
Explanation: cout is an object of ostream class which is a compiler defined class.
When we do “cout << obj" where obj is an object of our class, the compiler first looks for an operator function in ostream, then it looks for a global function.
One way to overload insertion operator is to modify ostream class which may not be a good idea. So we make a global method. Following is an example.
#include <iostream>
using namespace std;
class Complex
{
private:
int real;
int imag;
public:
Complex(int r = 0, int i =0)
{
real = r;
imag = i;
}
friend ostream & operator << (ostream &out, const Complex &c);
};
ostream & operator << (ostream &out, const Complex &c)
{
out << c.real;
out << "+i" << c.imag;
return out;
}
int main()
{
Complex c1(10, 15);
cout << c1;
return 0;
}
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.
Recommended Posts:
- C++ | Operator Overloading | Question 10
- C++ | Operator Overloading | Question 2
- C++ | Operator Overloading | Question 3
- C++ | Operator Overloading | Question 5
- C++ | Operator Overloading | Question 6
- C++ | Operator Overloading | Question 7
- C++ | Operator Overloading | Question 10
- C++ | Operator Overloading | Question 9
- C++ | Operator Overloading | Question 10
- C++ Program to concatenate two strings using Operator Overloading
- C++ program to compare two Strings using Operator Overloading
- Matrix operations using operator overloading
- Count number of Unique Triangles using Operator overloading
- C++ | Function Overloading and Default Arguments | Question 5
- C++ | Function Overloading and Default Arguments | Question 2
- C++ | Function Overloading and Default Arguments | Question 3
- C++ | Function Overloading and Default Arguments | Question 4
- C++ | Function Overloading and Default Arguments | Question 5
- Does C support function overloading?
- Function overloading and const keyword

