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:

#include <iostream>
using namespace std;
 
//interface (to be implemented by the classes)
class Printable{
public:
    //virtual function (to be overriden by the implementing class)
    virtual void print(ostream &os) const = 0;
};
 
//Overloading << operator
ostream& operator<<(ostream &os,const Printable &obj){
    obj.print(os);
    return os;
}
 
//Class I - implementing the Printable interface
class Account :public Printable{
public:
    double balance;
 
    Account(){
        balance = 9999;
    }
 
    //overriding the print function
    void print(ostream &os) const override {
        os << "Balance is: "<<balance<<endl;
    }
};
 
//Class II - implementing the Printable interface
class Student :public Printable{
public:
    int rollno;
 
    Student(){
        rollno = 700;
    }
 
    void print(ostream &os) const override {
        os << "Roll no: "<<rollno<< endl;
    }
};
 
int main()
{
    Printable *account = new Account();
    cout << *account;    //printing object directly
 
    Printable *student = new Student();
    cout << *student;    //printing object directly
 
    return 0;
}

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