Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does operator<< overloading work?

Tags:

c++

Given a class:

struct employee {
    string name;
    string ID;
    string phone;
    string department;
};

How does the following function work?

ostream &operator<<(ostream &s, employee &o)
{
 s << o.name << endl;
 s << "Emp#: " << o.ID << endl;
 s << "Dept: " << o.department << endl;
 s << "Phone: " << o.phone << endl;

 return s;
}

cout << e; produces formatted output for a given employee e.

Example output:

Alex Johnson
Emp#: 5719
Dept: Repair
Phone: 555-0174

I can't understand how the ostream function works. How does it get the parameter "ostream &s"?How does it overload the "<<" operator and how does the << operator work? How can it be used to write all of the information about an employee? Can someone please answer these questions in the layman's terms?

like image 309
tam bakaka Avatar asked Oct 30 '15 07:10

tam bakaka


2 Answers

This is called overload resolution. You've written cout << *itr. Compiler takes it as operator<<(cout, *itr);, where cout is an instance of ostream and *itr is an instance of employee. You've defined function void operator<<(ostream&, employee&); which match most closely to your call. So the call gets translated with cout for s and *itr for o

like image 105
stas.yaranov Avatar answered Oct 20 '22 03:10

stas.yaranov


Given an employee e;. the following code: cout << e;

will call your overloaded function and pass references to cout and e.

ostream &operator<<(ostream &s, const employee &o)
{
    // print the name of the employee e to cout 
    // (for our example parameters)
    s << o.name << endl; 

    // ...

    // return the stream itself, so multiple << can be chained 
    return s;
}

Sidenote: the reference to the employee should be const, since we do not change it, as pointed out by πάντα ῥεῖ

like image 23
oo_miguel Avatar answered Oct 20 '22 02:10

oo_miguel