Implement custom operator<<

Java’s toString() method unfortunately has no standard equivalent for C++ structs and classes. If you have custom structs/classes  and want to print some debugging information of that classes to standard output, the default way is to “concatenate” the properties of interest into an output stream. Say we have a struct BeadSequence (this is taken from the beads exercise in the USACO training camp) which represents a sequence of beads which has a length and a color:

If you want some debugging information on an instance (say beadSequence) of that class, you will normally do it like this:

You need to repeat this every time you want some information on a bead sequence – terribly cumbersome! What you would want to have instead is:

BeadSequence should “know” the interesting debugging information. To this end, you may override the operator<< which is used in conjunction with std::ostream objects to output data:

The following is a minimal working example:

2 comments

  1. That’s also quite an interesting idea which, in contrast to implementing operator<<, allows to use the string representation in circumstances other than just for std::ostream.

Leave a Reply

Your email address will not be published. Required fields are marked *

Please type the characters of this captcha image in the input box

Please type the characters of this captcha image in the input box