overloading operator<< to output object members without using friend function

chinnagaja picture chinnagaja · Jan 11, 2012 · Viewed 8.4k times · Source

I am refreshing cpp after a long gap, trying to understand the operator overloading methods. I tried to overload "operator<<" to output members of object. but I am unable to do so without using friend function. I am looking for a method without using friend function.

here is my class def:

class Add{
private:
int x;

public:
friend ostream& operator<<(ostream& ostr, Add const& rhs); //Method 1
void operator<<(ostream& ostr);                //Method 2
};

functions implementations

//Method 1
ostream& operator<<(ostream &ostr, Add const& rhs)
{
    ostr<<rhs.x;

return ostr;
}

//Method 2
void Add::operator<<(ostream& ostr)
{
    cout<<" using operator<< \n";
    ostr<<x;
}

calls from the main function

cout<<Obj_Add;  //calls the Method 1

Obj_Add<<cout;  //calls the Method 2

Now my question is, I would like to achieve the Method 1 type calls without using the friend function. But do not know, it is possible or not in cpp. I have tried few implementation but all are gives me compile errors. Please help me to understand the point i'm missing here.

Answer

Xeo picture Xeo · Jan 11, 2012

If you have public accessor functions in your class, or a stream-like one, you don't need the friendship with operator<<:

// v1
class foo{
public:
  int data() const{ return _data; }
private:
  int _data;
};

std::ostream& operator<<(std::ostream& o, foo const& f){
  return o << f.data();
}

// v2
class foo{
public:
  void stream_to(std::ostream& o){
    o << _data;
  }
private:
  int _data;
};

std::ostream& operator<<(std::ostream& o, foo const& f){
  f.stream_to(o);
  return o;
}

v2 has the added benefit of allowing stream_to to be a virtual function, which is helpful for polymorphic base-classes, so you don't need to reimplement operator<< for every derived class, only stream_to.