ghallio
ghallio

Reputation: 233

What's the right way to overload the stream operators << >> for my class?

I'm a bit confused about how to overload the stream operators for my class in C++, since it seems they are functions on the stream classes, not on my class. What's the normal way to do this? At the moment, for the "get from" operator, I have a definition

istream& operator>>(istream& is, Thing& thing) { // etc...

which works. It's not mentioned in the definition of the Thing class. I want it to be able to access members of my Thing class in its implementation - how do I do this?

Upvotes: 5

Views: 4777

Answers (4)

vladr
vladr

Reputation: 66721

Your implementation is fine. The only additional step you need to perform is to declare your operator as a friend in Thing:

class Thing {
public:
  friend istream& operator>>(istream&, Thing&);
  ...
}

Upvotes: 9

Tronic
Tronic

Reputation: 10430

There are several approaches and the right one really depends on what the class does.

Quite often it makes sense to have public API that allows reading the information, in which case the streaming operators do not need to access privates.

Probably the most popular approach is declaring the streaming functions friends of the class.

My favorite is providing a public Boost.Serialization style template function that can be used for streaming either way, as well as for other things.

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 839224

The other answers are right. In case it helps you, here's a code example (source):

class MyClass {
  int x, y;
public:
  MyClass(int i, int j) { 
     x = i; 
     y = j; 
  }
  friend ostream &operator<<(ostream &stream, MyClass ob);
  friend istream &operator>>(istream &stream, MyClass &ob);
};

ostream &operator<<(ostream &stream, MyClass ob)
{
  stream << ob.x << ' ' << ob.y << '\n';

  return stream;
}

istream &operator>>(istream &stream, MyClass &ob)
{
  stream >> ob.x >> ob.y;

  return stream;
}

Upvotes: 8

David Seiler
David Seiler

Reputation: 9725

You make your operator>> a friend of the Thing class.

Upvotes: 6

Related Questions