"Hans De Winter" <ha**********@tiscalinet.be> wrote in message
news:87**************************@posting.google.c om...
Hi,
I am really puzzled why my compiler does not accept the following code:-
--- CODE STARTS HERE ---
#include <iostream>
using namespace std;
class Foo
{
};
class Writer: public ostream
{
public:
Writer() : ostream(cout.rdbuf()) {}
Writer& operator<<(Foo&) {cout << "Hi"; return *this;}
};
int main(int argc, const char* argv[])
{
Foo f;
Writer w;
w << "Test"; // OK
w << f; // OK
w << '\t'; // OK
w << endl; // Not OK: Compiler complains about <unknown type>
return 0;
}
--- CODE STOPS HERE ---
Any hints? Many thanks in advance!
Hans
The operator<< that you want to be called is a member of ostream. Since you
have defined your own operator<< in a derived class, that operator hides the
operator in the base class. Try removing operator<< from Writer and the
fourth line will compile (but the second won't). The other operator<< that
you are successfully calling (for "Test" and '\t') are free functions, not
member functions, so aren't hidden by the operator<< in Writer.
Moral, don't derive from ostream, there are almost certainly better ways of
doing what you are trying to do, like deriving from streambuf.
john