toString override in C++

Alternative to Erik's solution you can override the string conversion operator.

class MyObj {
public:
    operator std::string() const { return "Hi"; }
}

With this approach, you can use your objects wherever a string output is needed. You are not restricted to streams.

However this type of conversion operators may lead to unintentional conversions and hard-to-trace bugs. I recommend using this with only classes that have text semantics, such as a Path, a UserName and a SerialCode.


 class MyClass {
    friend std::ostream & operator<<(std::ostream & _stream, MyClass const & mc) {
        _stream << mc.m_sample_ivar << ' ' << mc.m_sample_fvar << std::endl;
    }

    int m_sample_ivar;
    float m_sample_fvar;
 };

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.)

Tags:

C++

Tostring