toString override in C++

Aillyn picture Aillyn · Mar 2, 2011 · Viewed 45.8k times · Source

In Java, when a class overrides .toString() and you do System.out.println() it will use that.

class MyObj {
    public String toString() { return "Hi"; }
}
...
x = new MyObj();
System.out.println(x); // prints Hi

How can I accomplish that in C++, so that:

Object x = new Object();
std::cout << *x << endl;

Will output some meaningful string representation I chose for Object?

Answer

Erik picture Erik · Mar 2, 2011
std::ostream & operator<<(std::ostream & Str, Object const & v) { 
  // print something from v to str, e.g: Str << v.getX();
  return Str;
}

If you write this in a header file, remember to mark the function inline: inline std::ostream & operator<<(... (See the C++ Super-FAQ for why.)