Presentation is loading. Please wait.

Presentation is loading. Please wait.

Overloading the << operator

Similar presentations


Presentation on theme: "Overloading the << operator"— Presentation transcript:

1 Overloading the << operator
CSCE 121

2 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

3 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; } }

4 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.

5 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!!!

6 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.

7 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!!!

8 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 private data members since public accessors are not available. Avoid unless you have to!!!

9 References http://www.cplusplus.com/doc/tutorial/inheritance/


Download ppt "Overloading the << operator"

Similar presentations


Ads by Google