Contents Up << >>

How can I provide printing for a "class Fred"?

Provide a friend operator<<:

  	class Fred {
	public:
	  friend ostream& operator<< (ostream& o, const Fred& fred)
	    { return o << fred.i; }
 	  //...
	private:
	  int i;    //just for illustration
	};
We use a friend rather than a member since the "Fred" parameter is second rather than first. Input is similar, but the signature is:

 	istream& operator>> (istream& i, Fred& fred);
	                              // ^^^^^------- not "const Fred& fred"!