Click here to Skip to main content
15,881,380 members
Articles / Programming Languages / C++
Article

Overloading streams

Rate me:
Please Sign up or sign in to vote.
1.67/5 (17 votes)
7 Oct 20031 min read 33.8K   370   12   3
An article on overloading streams.

Introduction

I have found one difference between iostream library and standard libc in the way they handle I/O. The files really don’t care, to which device or regular file they are pointing to, as long as data is appropriate. Where as streams basically differ in the way they behave when it comes to files and console, as these functions are performed by different classes. It is quite well justified to behave that way.

But a programmer need not to worry whether his class is being outputted to file or standard console as long as stream supports operator << for built in data types.

There is a way to provide this transparency using templates.

Using the code

Assume that you have some class SomeClass which you want it to output to some stream. You really don’t care to which stream its being outputted.

It may be ostream(cout) or some fstream.

1.class SomeClass 
2.{ 
3.public: 
4.explicit SomeClass(int x) 
5.{ 
6.this->x = x ; 
7.} 
 

…………………………………….

…………………………………
8.template<class T> 
9.friend T& operator<<(T& os, const SomeClass &d) //Overloaded operator <<.
10.{ 
11.os<<d.x; 
12.return os; 
13.} 
 
14.private: 
15.int x; 
16.};

The same thing holds good for input streams and implementation can be found in the source code file.

Points of interest

If you are writing constructor for SomeClass, make sure that it is explicit. Otherwise it will try to convert d.x (Line no. :11) to SomeClass object thus resulting in compile time error. { I have wasted half an hour to figure it out. ;) }

Conclusion

Templates provide a great power when it comes to producing generic code. Use them to create reusable, generic code. Have fun;).

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralDon't need template Pin
James Curran14-Oct-03 14:37
James Curran14-Oct-03 14:37 
QuestionWhat's new? Pin
Anand Paranjpe8-Oct-03 20:06
Anand Paranjpe8-Oct-03 20:06 
QuestionWhat's new? Pin
Anand Paranjpe8-Oct-03 20:05
Anand Paranjpe8-Oct-03 20:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.