The output operator << works only with the primitive types. It is required to overload the operator in order to have a custom output of complex types like structs and classes.
Here’s is an example below :
We create a class named Customer
class Customer {
public:
string m_name;
string m_email;
int m_phone;
Customer(string name, string email, int phone)
{
m_name = name;
m_email = email;
m_phone = phone;
}
};
Now from our main function if we initialize and create 3 customers:
int main()
{
Customer c1("John Doe", "john@test.com", 22536598);
Customer c2("Mary Jane", "mary@test.com", 22536545);
Customer c2("Janet May", "janet@test.com", 22536598);
cout << c1;
cin.get();
return 0;
}
the line cout << c1 will not compile. It will throw the error
E0349 no operator “<<” matches these operands
cout is an object of the ostream class and its implementation of insertion operator (<<) does not cover user defined types. It is overloaded only for arithmetic types, stream buffers and manipulators.
It is clear from the above fact that if we overload the insertion operator (<<) in our complex type we can get cout to output our data the way we want.
I will overload the insertion operator for our Customer class. Our code will look like this
class Customer {
public:
string m_name;
string m_email;
int m_phone;
Customer(string name, string email, int phone)
{
m_name = name;
m_email = email;
m_phone = phone;
}
friend ostream& operator<<(std::ostream& os, const Customer &p);
};
ostream & operator <<(std::ostream &os, const Customer& c) {
os << "Name: " << c.m_name << endl << "Phone:" << c.m_phone << endl << "Email:" << c.m_email << endl;
return os;
}
Note that insertion operator is overloaded globally. This is because operator requires lhs parameter to be of the type of ostream, which is possible only if the overloaded operator is a member of ostream.
The output from our main function will be as below:
Name: John Doe Phone:22536598 Email:john@test.com