Overloading <<

Hello,

When writing a class, sometimes I would like to have it output seamlessly to an ostream. For example, say I have a class called Thing.

1
2
3
4
5
..
Thing x;
..
cout << "The thing is " << x << endl;
..


whereupon it would output something meaningful.

Now suppose I have Thing defined in its own header file, thing.h and implemented in thing.cpp.

Where is the proper place to put the line:
std::ostream& operator<< ( std::ostream& , const Thing& );
?

My first thought was to include it in thing.h.
Now this works provided I include <iostream> in the header file itself.

But recalling way back (90s) to college when I was taught to use C++, I was told that it is bad form to include a header file in a header file. I should properly include <iostream> in the associated .cpp file and simply have a line like
class std::ostream;
in the header (I don't remember what this particular technique is called, but it had a name).

When I do this, it won't compile. Can someone tell me the proper way of accomplishing what I intend? Is the only solution to include <iostream> in my thing header file?

BTW the compile error is:
bint.h:4:12: error: ‘ostream’ in namespace ‘std’ does not name a type


Thanks!
it is bad form to include a header file in a header file
This is false. At least, I've never heard anything like that.
It's true that under certain conditions and if you're not careful it can greatly increase compile time, but if you have a declaration in a header that needs a declaration that's in another header, there isn't really much you can do, specially with function declarations.

Go ahead and include <iostream>.
All right. Glad to know that's acceptable coding behavior. Thanks!
Topic archived. No new replies allowed.