overloading the i/o operator

In this below example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Point
{
private:
    double m_dX, m_dY, m_dZ;
 
public:
    Point(double dX=0.0, double dY=0.0, double dZ=0.0)
    {
    m_dX = dX;
    m_dY = dY;
    m_dZ = dZ;
    }
 
    friend ostream& operator<< (ostream &out, Point &cPoint);
 
    double GetX() { return m_dX; }
    double GetY() { return m_dY; }
    double GetZ() { return m_dZ; }
};
 
ostream& operator<< (ostream &out, Point &cPoint)
{
    // Since operator<< is a friend of the Point class, we can access
    // Point's members directly.
    out << "(" << cPoint.m_dX << ", " <<
        cPoint.m_dY << ", " <<
        cPoint.m_dZ << ")";
    return out;
}

Point cPoint(5.0, 6.0, 7.0);
cout << cPoint;


When << is invoked on cout, since Point is defined as a friend of that method and it has a matching parameter list, the << defined in Point class gets called. But what is confusing is this line:
1
2
3
4
    out << "(" << cPoint.m_dX << ", " <<
        cPoint.m_dY << ", " <<
        cPoint.m_dZ << ")";
    return out;

In that situation, << does not call the overloaded function, but rather calls the << method defined in the i/o library, which prints a message to the controlling terminal. So once it prints the message to the terminal, it then returns the out instance. Why return the out instance rather than a boolean like true? As you can see from the example, once the message is printed to terminal, out is not used anymore.
ok I read more of tutorial and it explains why: so we can chain endl; to the output object.
You return the stream so that multiple <<'s can be "chained"

1
2
Point p;
cout << "My point is:  " << p << ", got it?";


Each of these << operators resolve independently. Each one returns the output stream so that it can be used as the left side of the following << operator... so:
 
cout << "My point is:  "

happens first... then that returns the output stream by reference (which in this case would be returning cout). So then cout is used for the NEXT operator:
 
cout << p

Which again returns cout... so it can be used yet again:
 
cout << ", got it?";


Another way to visualize it is like this:

1
2
3
4
5
6
7
cout << "My point is:  " << p << ", got it?";

// is the same as this:

ostream& a = (cout << "My point is:  ");
ostream& b = (a << p);
ostream& c = (b << ", got it?");


If you return a boolean... then you'll be trying to use the << operator to output to a boolean instead of to an ostream.. which would be nonsense.
Topic archived. No new replies allowed.