Operator Overloading For Input And Output

Input and output operators (>> and <<) can be predefined too. Those operators can only be predefined outside the class.

Input operator

Syntax:

Notice that the class object is passed by reference (using &). This way the class object can be modified inside the function.

Example:

User's input:

Output:

>> operator is called at line 47 and predefined at lines 30 - 42.

Output operator

Syntax:

Example:

Output:

<< operator is called at line 41 and predefined at lines 30 - 36.

File Stream Example

So far the only stream that was used is the console - through cin and cout.

Except the console we can also use other streams (like the file stream) for the predefined input and output operators.

Let's use the file stream.

So if we have input-file.txt with content:

And the following cpp code:

Then the console result would be:

Also a file named output-file.txt will be created with content:

Explanation:

  • At lines 66 input-file.txt file is opened.
  • At line 67 the file content is red and member's values are set for the personFromInputFile object.
  • The way the file is red is defined in the operator>> function (lines 46 - 58).
  • At line 70 personFromInputFile object is printed. It's name and age are the same as those specified in the input-file.txt file.
  • At line 80 the name and age are written in the "output-file.txt. The way the are written is specified in the operator<< function (lines 37 - 43).