Why does toString() exist? It seems useless.

Sean Kelly sean at invisibleduck.org
Fri Aug 22 12:46:14 PDT 2008


Leandro Lucarella wrote:
> Don, el 18 de agosto a las 12:41 me escribiste:
>> I cannot understand the rationale for a toString() member function which doesn't 
>> support formatting.
> 
> I think is useful only for debugging purposes.
> 
>> C++ got around this by giving state to the iostream classes.
> 
> I think C++ formatting is heavily ill. All the manipulator stuff is
> madness.

It's horrific but surprisingly flexible.  I've created stateful 
formatters for various protocols and made it work all invisibly with the 
formatting hooks provided in C++.  For example:

    std::cout << a << b << c << std::flush;

The above may perform lazy output of structured XML, some binary 
encoding, etc.  It might be possible to get close with toString, but 
because it returns an array rather than writing into a buffer some of 
the flexibiliy (like lazy encoding) would definitely be lost.

My experience with Java suggests that toString is meant for debugging 
purposes anyway.  It's rare that an object will produce meaningful 
user-level output with its toString method.


Sean


More information about the Digitalmars-d-learn mailing list