In this article, we will write a few C++ programs to print the object directly by overloading insertion operator (<<) and creating an interface.

Before proceeding further make sure that you know these:

Output

Notice in the program we have directly used cout stream with an object (i.e cout << *account).

Explanation

We have first created an interface ‘Printable’ so that we can inherit it to the different classes and override its print function to output the respective attributes of the class.

The override print function will be called by the object of the same class from the overloaded << function. This will happen when we use the insertion operator (<<) with the object in the main function. You can notice we have used two parameters in the overloading function i.e ostream, Printable. Since the different class has inherited Printable interface, therefore, we can say that all those class is a Printable.

For example, we inherited ‘Printable’ interface to ‘Account’ class and override the print function. In print function, we have outputted the balance using ostream argument. The same print function will be called from the overloaded << function and the following is being called from the main. The same we have done with other class 'Student'. Because of the interface we only had to override the print function and did not require to explicitly overload << operator for every class.

If you have any doubts then comment below.

Leave a Reply

Close Menu