Main Content

Formatting and outputting your own classes in C++

Archive - Originally posted on "The Horse's Mouth" - 2015-10-30 11:09:50 - Graham Ellis

When you output an object in C++, you pass it to an output stream such as std::cout or cout. If the thing you're outputting is a string, or an integer, float, some other primitive or a standard system object, that's all you need to do and the formatting is taken care of for you. But what if you're outputting your own object?

The first option you have is to call methods that will convery your object's values into primitives which you ca output usig standard techniques. The alternative is for you to overload the operator<< method for the ostream class to provide an extra output method to handle your output. Here's an example of such a method, together with a method in the class we're handling to do the actual formatting:

  void Mtbs::print(ostream *os)
    { *os << "Attention every " << value << " cups [" << descriptor << "]" ;
    }
  
  ostream &operator<<(ostream &os, Mtbs &mt) {
    mt.print(&os);
    return os;
    }


Complete example [here]