C++ istream / ostream equivalent ?

Jonathan M Davis jmdavisProg at gmx.com
Wed Dec 1 11:59:17 PST 2010


On Wednesday, December 01, 2010 11:40:11 Ali Çehreli wrote:
> Matthias Pleh wrote:
>  > class B{ string toString() {return "screen output routine here";}}
> 
> Isn't the 'override' keyword required? (Perhaps required only in D2?)
> 
> I find string.format very helpful in toString() member functions.
> 
> Finally, I still don't know whether the 'const'ness of the member
> function is required, allowed, or completely wrong. :)
> 
> import std.string;
> 
> class A
> {
>      override string toString() const
>      {
>          return format("My %s formatted string: %s", "lovely", 42);
>      }
> }
> 
> Ali

override is required if you compile with -w. If you don't use -w, the compiler 
won't complain, but I'm not sure that it actually overrides the function in that 
case. So, yes override should be there.

Object's toString() is not currently const-correct. It isn't const. So, 
currently, when overriding toString(), you don't have to make it const. However, 
you _can_ make it const if you want to (and honestly, Object's toString() 
_should_ be const; it's just among the changes that need to be made to Object to 
make it properly const-correct: http://is.gd/i3KUJ ). Making a non-const 
function const when overriding it is adding guarantees, not loosening them, so 
it works.

Be forewarned, however, that because of bug http://is.gd/i3Lc2 ), _struct_'s 
toString() cannot be const (or at least, you need a non-const version in 
addition to a const one if you have a const one). Classes don't have that 
problem though.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list