11

Is there a way to overload the << operator, as a class member, to print values as a text stream. Such as:

class TestClass {
public:
    ostream& operator<<(ostream& os) {
        return os << "I'm in the class, msg=" << msg << endl;
    }

private:
    string msg;
};


int main(int argc, char** argv) {
    TestClass obj = TestClass();
    cout << obj;

    return 0;
}

The only way I could think of was to overload the operator outside of the class:

ostream& operator<<(ostream& os, TestClass& obj) {
    return os << "I'm outside of the class and can't access msg" << endl;
}

But then the only way to access the private parts of the object would be to friend the operator function, and I'd rather avoid friends if possible and thus ask you for alternative solutions.

Any comments or recommendations on how to proceed would be helpful :)

32

6 Answers 6

14

It needs to be a non-member, since the class forms the second argument of the operator, not the first. If the output can be done using only the public interface, then you're done. If it needs access to non-public members, then you'll have to declare it a friend; that's what friends are for.

class TestClass {
public:
    friend ostream& operator<<(ostream& os, TestClass const & tc) {
        return os << "I'm a friend of the class, msg=" << tc.msg << endl;
    }

private:
    string msg;
};
2
9

You have stumbled across the canonical way to implement this functionality. What you have is correct.

1
  • This is not correct because it won't compile. In the setup from the question one would have to write something ugly like obj<<cout;.
    – phinz
    Sep 27, 2018 at 16:41
6

I believe one popular way to do this is a non-member, non-friend free operator<< that calls a public non-virtual print method within your class. This print method can either do the work or delegate to a protected virtual implementation.

class TestClass {
public:
    ostream& print(ostream& os) const {
        return os << "I'm in the class, msg=" << msg << endl;
    }

private:
    string msg;
};


ostream& operator<<(ostream& os, TestClass& obj) {
    return obj.print(os);
}

int main(int argc, char** argv) {
    TestClass obj;
    cout << obj;

    return 0;
}
5
  • I support this solution above using a friend declaration. It maintains encapsulation and gets the job done.
    – broc
    Dec 12, 2011 at 17:05
  • @broc I don't see any real difference in the encapsulation. In one case, the author of the class explicitly gives access rights to a single instance of operator<<(); in this method, he explicitly gives access rights to a function named print(). Where is the difference? (There may be other reasons to use the print() method, but more or less encapsulation isn't one of them.) Dec 12, 2011 at 17:34
  • @JamesKanze You could argue that declaring a member public is just the author giving access rights to everyone explicitly and hence it does not break encapsulation. Whether you buy this or not depends on where you draw the line. I personally think that the line must be drawn as far as possible in the opposite direction; having the print method allows you to distribute the class in a .dll, distribute it without source and still allows the user of the library to write their overloaded operator<< for their convenience. Can you get any more encapsulated? From the perspective...
    – broc
    Dec 13, 2011 at 18:57
  • @JamesKanze of just the language I can't disagree with you, however, the language is used to create an executable or a library and I think that for the purpose of developing professionally, the concept of encapsulation must reach further than just thinking in terms of the language.
    – broc
    Dec 13, 2011 at 19:00
  • @broc Declaring a member public loosens encapsulation, since it makes the member part of the public interface. Declaring a function friend makes that function part of the class' public interface; by making a function part of the interface, rather than data, you are actually increasing encapsulation. Too many functions (or poorly designed functions, like getters and setters) weaken encapsulation too, but in this regard, whether the function is a friend or a member is irrelevant. Dec 14, 2011 at 9:52
2

You can make it member of the class, that is on the left of <<, which is ostream in your case.

What you can do, though, is have a base class with void do_stream(ostream& o); member for all your streamables and non-member operator<< that would call it.

1
  • I don't. I'm just stating the fact that if one wants it to be a class member, the class should be std::ostream. Which basically means no, you don't want it be a class member. Dec 12, 2011 at 18:51
0

You're right, that's the only way to implement the stream operator - outside the class.

You need to declare the method as friend.

That's how it's done.

4
  • 1
    There's usually no need to declare the function as a friend; anything you output is part of the public interface of the class. (It's often appropriate to declare it as a friend in a template, in order to use the Barton and Nackman trick, but that's a different issue.) Dec 12, 2011 at 14:55
  • This is seriously not the only way to implement it. I've seen and implemented most stream operators without binding them as friend. Only were necessary, friend should be used. Dec 12, 2011 at 16:39
  • @phresnel I tend to use the print method a lot, with class templates. Not to gain access, but to be able to define the function within the class. Dec 12, 2011 at 17:35
  • In his case, the member is private, so friendship is required. It's much simpler than adding getters just to be used by the stream. Dec 12, 2011 at 17:37
0

You have to make it a non member (as the first parameter is not your class).

But you can write it inside your class definition (as a friend):

class TestClass
{
public:
    // Have a nice friend.
    // This tightly binds this operator to the class.
    // But that is not a problem as in reality it is already tightly bound.
    friend ostream& operator<<(ostream& os, TestClass const& data)
    {
        return os << "I'm in the class, msg=" << data.msg << endl;
    }

private:
    string msg;
};

I see nothing wrong with making this a friend.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.