Why does toString() exist? It seems useless.

bearophile bearophileHUGS at lycos.com
Mon Aug 18 05:30:21 PDT 2008


Don Wrote:
> I cannot understand the rationale for a toString() member function which 
> doesn't support formatting.

I think the rationale is that it's a simple function that performs a simple thing with an easy to use and easy to learn syntax, I have found it useful often.

For more complex purposes you can write your own printing methods, or you can write a method that changes the printing state of the class/struct, that is later read and used when you call toString() and used to change its behavior.

So I have created a graph class that by default when you call toString() gives a compact and simple textual representation of the graph. Then there are other methods, one that returns a string that shows the matrix of links, another that shows the weights of the arcs too, etc. There is also the possibility to modify the printing defaults with another method, to then later toString() acts differently.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list