Overloading the << operator CSCE 121 J. Michael Moore
Output Custom classes No problem we can overload Class helper function Want to use the output operator (<<) for them! No problem we can overload Class helper function
Class (Version 1) class MyClass { int data1; int data2; public: MyClass() : data1(0), data2(0) {} MyClass (int data1 = 0; int data2 = 0) : data1(data1), data2(data2) {} int getData1() { return data1; } int getData2() { return data 2; } }
Can’t be a method of the class being output! Create Function ostream& operator<<(ostream& os, const MyClass& mc) { // Do streaming output here return os; } Can’t be a method of the class being output! Always returns a reference to an ostream. First parameter is always an ostream passed by reference. (NOT const!) Second parameter is always the class being output passed by const reference. Always returns the ostream parameter that was passed in.
PREFERRED!!! Function (Version 1) ostream& operator<<(ostream& os, const MyClass& mc) { // Do streaming output here os << mc.getData1() << “ “ << mc.getData2(); return os; } Uses public accessor methods to get data to print. PREFERRED!!!
Dilemma Sometimes we have private / protected data we want to include in output from the << operator, but we don’t want public accessors for that data. We could just make the private / protected data public… But we really don’t want to do that. Solution: Declare class / function as a friend.
Friend allows access to private data members. Class (Version 2) class MyClass { int data1; // don’t want a public accessor int data2; // don’t want a public accessor friend ostream& operator<<(ostream& so, const MyClass& mc); public: MyClass() : data1(0), data2(0) {} MyClass (int data1 = 0; int data2 = 0) : data1(data1), data2(data2) {} } Friend allows access to private data members. Avoid unless you have to!!!
Avoid unless you have to!!! Function (Version 2) ostream& operator<<(ostream& os, const MyClass& mc) { // Do streaming output here os << mc.data1 << “ “ << mc.data2; return os; } Directly accesses public data members since public accessors are not available. Avoid unless you have to!!!
References http://www.cplusplus.com/doc/tutorial/inheritance/ https://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx