Click here to Skip to main content
13,290,176 members (57,838 online)
Click here to Skip to main content
Add your own
alternative version


12 bookmarked
Posted 7 Oct 2003

Overloading streams

, 7 Oct 2003
Rate this:
Please Sign up or sign in to vote.
An article on overloading streams.


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 
4.explicit SomeClass(int x) 
6.this->x = x ; 


8.template<class T> 
9.friend T& operator<<(T& os, const SomeClass &d) //Overloaded operator <<.
12.return os; 
14.private: x; 

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. ;) }


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


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


About the Author

Prasad Kulkarni
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralDon't need template Pin
James Curran14-Oct-03 15:37
memberJames Curran14-Oct-03 15:37 
QuestionWhat's new? Pin
Anand Paranjpe8-Oct-03 21:06
sussAnand Paranjpe8-Oct-03 21:06 
QuestionWhat's new? Pin
Anand Paranjpe8-Oct-03 21:05
sussAnand Paranjpe8-Oct-03 21: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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171207.1 | Last Updated 8 Oct 2003
Article Copyright 2003 by Prasad Kulkarni
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid