Using "friend" for overloading of << operator.

Originally published 2016-02-23 · Boris Ivanov

1. Overloading with free function.


#include <iostream>
using namespace std;
class Basic{
public:

    Basic(int x, int y): _x(x), _y(y){}
    int _x;
    int _y;

};

ostream& operator<<(ostream& os, const Basic& obj) {
    os << obj._x << "," << obj._y;
    return os;
}


int main(int argc, char *argv[])
{
    Basic a = Basic(10,20);
    cout << a << endl;
    return 0;
}

2. Overloading with member function.


#include <iostream>

using namespace std;

class Basic{

public:

    Basic(int x, int y): _x(x), _y(y){}
    void private_stream(ostream& os) const
    { os << _x << ":" << _y; }

private:
    int _x;
    int _y;

};

inline ostream& operator<<(ostream& os, const  Basic& obj) {
    obj.private_stream(os);
    return os;
}


int main(int argc, char *argv[])
{
    Basic a = Basic(10,20);
    cout << a << endl;
    return 0;
}

3. overloading with "friend" function.


#include <iostream>
using namespace std;
class Basic{

public:

    Basic(int x, int y): _x(x), _y(y){}
    friend ostream& operator<< (ostream& , const Basic& );

private:
    int _x;
    int _y;

};

inline ostream& operator<<(ostream& os, const  Basic& obj) {
    os << obj._x << ":" << obj._y;
    return os;
}


int main(int argc, char *argv[])
{
    Basic a = Basic(10,20);
    cout << a << endl;
    return 0;
}