Defining input and output operators cheatsheet.

When defining a new type in C++, one of the things that need to be taken care of is how to read and write them. Suppose that we have defined a new type.

struct My_new_type {

Now you want to be able to read and write your new type.

How is it done? One of the approaches (applicable to many other languages) is to define functions that do just that.

void read_my_new_type(istream& is, My_new_type& my_object);
void display_my_new_type(ostream& os, My_new_type my_object);

or one can use overloaded operators, to make the input and output more uniform.

ostream& operator << (ostream& os, My_new_type my_object);

for output and

istream& operator >> (stream& is, My_new_type& my_object);

for input.

The second way is more concise when used in code because you can just write

cout << my_object;

instead of

display_my_new_type(cout, person);

On the other hand the second form has the advantage of arguably being more clear sometimes. What the function does is clearly displayed in its name while the fact that << means output operator is not always clear, since << can mean bit wise shift as well.

However there are few things to keep in mind when writing a user input function or operator.

Input function or operator has the following form. It is important to handle the input errors, otherwise things get broken easily and quickly…

my_input_function(istream& is, My_new_type& my_object) {
    initialize the values to read;
    read the values;
    if(read wasn't successful) return is;
    if(wrong format) {
        set the stream to fail (usually done by is.clear(ios_base::fail_bit) );
        return is;
    set the new value of my_object;

Output is usually easier, because error handling usually done by the output stream itself.

my_output_function(istream& is, My_new_type my_object) {
    os << object data in desired format;

Things can change but that's the general form.
That's what I do when defining input and output operators for new type first tine to get things working quickly.

I would like to hear your comments and know if you have found any errors.

Happy coding.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s