Miscellaneous Operators (<<, >>, [], ())
Discover the power of special ostream operators (<<, >>) that enable customized printing of user-defined data types using cout on both the console and file stream.
Overloading I/O operators
The I/O (Input/Output) objects cin/cout
don't work for user-defined data types. Overloading I/O operators refers to the process of defining and customizing the operators (<<
and >>
) for user-defined data types. This allows us to control how our objects are formatted when outputting to a console or file streams or how they are read from a stream (iostream/ifstream
).
When overloading I/O operators, we have two approaches: friend
functions and global functions. We use friend
functions when we need access to the private
members of the class. To achieve this, we declare them as friends using the friend
keyword, in their prototypes within the class and then define them outside the class. (We can define them inside the class as well.) This ensures that the functions can effectively work with the private members while maintaining proper encapsulation. As a result, we can elegantly customize I/O operations for user-defined data types in a clean and efficient manner.
For example, to overload the output operator (<<
) for a user-defined MyClass
class, we can define a friend function as follows:
Get hands-on with 1200+ tech skills courses.