Using “friend” for overloading of << operator.

1. Overloading with free function.

  • Function not part of Class.
  • Basic class accessed by Reference not to make Copy and as Const as we not gonna change it.
  • Only public members of class accessable
#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.

  • Function is part of Class.
  • Basic class accessed by Reference not to make Copy and as Const as we not gonna change it.
  • Even private members of class accessable
#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.

  • Friend Function declared in Class but defined outside.
  • Basic class accessed by Reference not to make Copy and as Const as we not gonna change it.
  • Even private members of class accessable
#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;
}

Leave a Reply

Your email address will not be published. Required fields are marked *