Summary: In this tutorial, we’ll learn how to overload the insertion operator (<<) to print an object directly using cin in C++.

To understand this topic, you should have knowledge about the following C++ topics:

Output:

Balance is: 9999
Roll no: 700


Explanation:

We have created an interface called Printable so that it can be inherited by different classes and its print function can be overridden to output the respective properties of the class.

Each class extends to the Printable interface and overrides its print function to define which properties of the class should be printed.

The overridden print function is called whenever we output any instance of the class using cout and << operator.

This happens because we have overloaded the << operator to implicitly call the print function of the respective classes.

The function overloading << operator accepts two objects as parameters i.e. ostream, Printable, therefore is invoked whenever any instance of Printable is operated by the ostream object (i.e. cout << Printable()).

Since any class implementing the Printable interface becomes a Printable, so the same overloading function is invoked when an instance of the same is printed.

For example, we inherited the ‘Printable‘ interface into the ‘Account‘ class and override the print function. In the print function, we output the balance using the ostream argument.

The same print function is being called from the overloaded << function and preceded by the output call in the main function (i.e. cout << *account).

The same happend for the object of the Student class.

Because of the general Printable interface, we only had to override the print function otherwise we would have to explicitly overload << operator for every class.

Leave a Reply

19 + 18 =