One of the advantages of using the iostream objects is that you can customize them to support your own classes. I will show how to overload ostream's operator << so that it can display a user-defined object.
Suppose you declared the following class:
class student
{
private:
string name;
string department;
public:
student(string n = "", string dep = 0)
: name(n), department(dep) {}
string get_name() const { return name; }
string get_department () const { return department; }
void set_name(const string& n) { name=n; }
void set_department (const string& d) {department=d;}
};
And you want to be able to use it in a cout statement as follows:
student st("Bill Jones", "Zoology"); // create instance
cout<<st; // display student's details
First, you need to overload the operator << of class ostream (note that cout is an instance of ostream). The canonical form of such an overloaded << is this:
ostream& operator << (ostream& os, const student& s);
The overloaded << returns a reference to an ostream object and takes two parameters by reference: an ostream object and a user-defined type. The user-defined type is passed as a const parameter because the output operation doesn't modify it.
The body of the overloaded << inserts members of the user-defined object into the ostream object:
os<<s.get_name()<<'\t'<<st.get_department()<<endl;
Make sure that the members inserted are separated by a tab, newline or space so that they appear as if they were concatenated when displayed on the screen. Remember also to place the endl manipulator at the end of the insertion chain to force a buffer flush. Finally, the overloaded operator should return the ostream object after the members have been inserted to it. This will enable you to chain several objects in a single cout statement:
student s1, s2;
cout<<s1<<s2; // chaining multiple objects
The insertion operations and the return statement can be accomplished in a single statement:
ostream& operator << (ostream& os, const student& s)
{
return os<<s.get_name()<<'\t'<<s.get_department()<<endl;
}
Now you can use the overloaded <<in your code:
int main()
{
student st("Bill Jones", "Zoology");
cout<<st;
}
As expected, this program displays:
Bill Jones Zoology