C++ equivalent of Java's toString?

c++

Solution

In C++ you can overload `operator<<` for `ostream` and your custom class:

class A {
public:
  int i;
};

std::ostream& operator<<(std::ostream &strm, const A &a) {
  return strm << "A(" << a.i << ")";
}

This way you can output instances of your class on streams:

A x = ...;
std::cout << x << std::endl;

In case your `operator<<` wants to print out internals of class `A` and really needs access to its private and protected members you could also declare it as a friend function:

class A {
private:
  friend std::ostream& operator<<(std::ostream&, const A&);
  int j;
};

std::ostream& operator<<(std::ostream &strm, const A &a) {
  return strm << "A(" << a.j << ")";
}

Problem

I'd like to control what is written to a stream, i.e. `cout`, for an object of a custom class. Is that possible in C++? In Java you could override the `toString()` method for similar purpose.

Original source