12.10 — Printing inherited classes using operator<<

Consider the following program that makes use of a virtual function:

By now, you should be comfortable with the fact that b.print() will call Derived::print() (because b is pointing to a Derived class object, Base::print() is a virtual function, and Derived::print() is an override).

While calling member functions like this to do output is okay, this style of function doesn’t mix well with std::cout:

In this lesson, we’ll look at how to override operator<< for classes using inheritance, so that we can use operator<< as expected, like this:

The challenges with operator<<

Let’s start by overloading operator<< in the typical way:

Because there is no need for virtual function resolution here, this program works as we’d expect, and prints:


Now, consider the following main() function instead:

This program prints:


That’s probably not what we were expecting. This happens because our version of operator<< that handles Base objects isn’t virtual, so std::cout << bref calls the version of operator<< that handles Base objects rather than Derived objects.

Therein lies the challenge.

Can we make Operator << virtual?

If this issue is that operator<< isn’t virtual, can’t we simply make it virtual?

The short answer is no. There are a number of reasons for this.

First, only member functions can be virtualized -- this makes sense, since only classes can inherit from other classes, and there’s no way to override a function that lives outside of a class (you can overload non-member functions, but not override them). Because we typically implement operator<< as a friend, and friends aren’t considered member functions, a friend version of operator<< is ineligible to be virtualized. (For a review of why we implement operator<< this way, please revisit lesson 9.4 -- Overloading operators using member functions).

Second, even if we could virtualize operator<< there’s the problem that the function parameters for Base::operator<< and Derived::operator<< differ (the Base version would take a Base parameter and the Derived version would take a Derived parameter). Consequently, the Derived version wouldn’t be considered an override of the Base version, and thus be ineligible for virtual function resolution.

So what’s a programmer to do?

The solution

The answer, as it turns out, is surprisingly simple.

First, we set up operator<< as a friend in our base class as usual. But instead of having operator<< do the printing itself, we delegate that responsibility to a normal member function that can be virtualized!

Here’s the full solution that works:

The above program works in all three cases:


Let’s examine how in more detail.

First, in the Base case, we call operator<<, which calls virtual function print(). Since our Base reference parameter points to a Base object, b.print() resolves to Base::print(), which does the printing. Nothing too special here.

In the Derived case, the compiler first looks to see if there’s an operator<< that takes a Derived object. There isn’t one, because we didn’t define one. Next the compiler looks to see if there’s an operator<< that takes a Base object. There is, so the compiler does an implicit upcast of our Derived object to a Base& and calls the function (we could have done this upcast ourselves, but the compiler is helpful in this regard). This function then calls virtual print(), which resolves to Derived::print().

Note that we don’t need to define an operator<< for each derived class! The version that handles Base objects works just fine for both Base objects and any class derived from Base!

The third case proceeds as a mix of the first two. First, the compiler matches variable bref with operator<< that takes a Base. That calls our virtual print() function. Since the Base reference is actually pointing to a Derived object, this resolves to Derived::print(), as we intended.

Problem solved.

12.x -- Chapter 12 comprehensive quiz
12.9 -- Dynamic casting

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. I have a similar but not exact problem in one TD, out TD "exercise" id given just after inheritance, so the virtual is not known yet, I can't use it.

    I have class Groupe which contains a vector of pointers towards users, I want to print every user in the list but some are premium users and some are regular both are child's from base user class.

    ostream & operator<<(ostream& os, const Groupe& groupe)
        os << "L'evenement " << groupe.nom_ << " a coute un total de " << groupe.getTotalDepenses() << " :  \n\n";
        for (unsigned i = 0; i < groupe.utilisateurs_.size(); i++) {
            os << *groupe.utilisateurs_[i];
        os << endl;

        if (groupe.transferts_.size() != 0) {
            os << "Les transferts suivants ont ete realiser pour equilibrer  : " << endl;
            for (unsigned i = 0; i < groupe.transferts_.size(); i++) {
                os << "\t";
                os << *groupe.transferts_[i];
            cout << endl;
        else {
            os << "Soit les comptes suivants :" << endl;
            for (unsigned i = 0; i < groupe.utilisateurs_.size(); i++) {
                os << groupe.utilisateurs_[i]->getNom() << " : " << groupe.comptes_[i] << endl;
        os << endl;

        return os;

    and the operator << for userPremium is :
    ostream & operator<<(ostream & os, const UtilisateurPremium & utilisateur)
        Utilisateur ut = static_cast<Utilisateur>(utilisateur);
        os << ut;
        os << endl << "Taux :" << utilisateur.taux_
           << "Nbr jours :" << utilisateur.joursRestants_;//????? need for virtual
        return os;

    and siilar one for regular ,

    the mother user printing is :
    ostream& operator<<(ostream& os, const Utilisateur& utilisateur)  
        os << "Utilisateur : " << utilisateur.nom_ << " (" << utilisateur.valeurEnum(utilisateur.type_) <<")" << " a depense pour un total de : "
        << utilisateur.getTotalDepenses() << endl;
        os << "\t Liste de depenses : " << endl;

        for (unsigned i = 0; i < utilisateur.depenses_.size(); i++) {
            os << "\t\t";
            os << *utilisateur.depenses_[i];
        os << "Interet :" << utilisateur.interet_<< endl;

        return os;

    the proplem is the printout is as follow :

    L'evenement Madrid a coute un total de 1480 :

    Utilisateur : alex (Premium) a depense pour un total de : 1050
             Liste de depenses :
                    Achat : d6 Prix : 1000 Type : groupe;
                    Achat : d8 Prix : 50 Type : groupe;
    Interet :8.66667
    Utilisateur : Max (Premium) a depense pour un total de : 1480
             Liste de depenses :
                    Achat : d6 Prix : 1000 Type : groupe;
                    Achat : d7 Prix : 430 Type : groupe;
                    Achat : d8 Prix : 50 Type : groupe; ........ect

    the program see my premium users as basic users,  so it neglects the particular additional printing for premium which is os <<"Taux:" << utilisateur.taux_<< "Nbr jours :" << utilisateur.joursRestants_;

    how can I fix this !! to make the program print the regular as regular and premium as premium without doing it manually in the Group print with if condition to ass the extra values for regular or premium.

    thanks for reading, and I appreciate your reply because its a very complicated TD contains 19 CPP and .h files

  2. Hi Alex,

    I have one question.

    You mentioned as below.

    In the Derived case, the compiler first looks to see if there’s an operator<< that takes a Derived object. There isn’t one, because we didn’t define one. Next the compiler looks to see if there’s an operator<< that takes a Base object. There is, so the compiler does an implicit upcast of our Derived object to a Base& and calls the function

    So my question :: does above thing just applicable to << operator, or does it applicable to all other operator as well ?

  3. [code]
    friend std::ostream& operator<<(std::ostream &out, const Base &b)
            // Delegate printing responsibility for printing to member function print()
            return b.print(out);

    Why dont we need to have the this* pointer in the parameter in the print function

    • Hi Aron!

      The this pointer is automatically passed behind the scenes, you don't need to do it manually. In your example a pointer to @b is passed as the 'this' parameter to @print.

      PS: Closing code tags use forward slashes

  4. Hi Alex,

    Thanks for your awesome tutorials. In the 1st example, there is a code snippet as below

    There are no initializations required for Base class. Then is it mandatory to call Base() constructor in the initializer list of Derived class in this case?

  5. I really like this method. I used it in my program and feel that it's more concise and beautiful now. Thanks very much!

    • I'm not sure this qualifies, since the template method design pattern defers some steps to the subclass. This essentially just routes the entire call to a virtualizable function.

  6. Hi Alex,

    I have same query as above if derived have not any function (operator<<) then how it will call from Derived ref.

    #include <iostream>
    using namespace std;
    class Base
        Base(){    }
        virtual void print() const
            cout<< "Base";
        friend ostream& operator<<(ostream &out, const Base &b)
            out<< "Base Overload  :: ";
            return out;
    class Derived : public Base
        Derived() : Base() {}
        virtual void print() const
            cout<< "Derived";
    /*    friend ostream& operator<<(ostream& out, const Derived &b)
            cout<< "Derived Overload" ;
            return out;
    int main()
        Derived d;
        Derived &b = d;
        cout<<"B is "<<b<<endl;
        return 0;

    • This is easily answered by trying it.

      In this case, because there is no D::operator<<, it will call B:operator<<. B::operator<< will then call virtual function print(), which will resolve to D::print().

  7. Just out of curiosity. Can I do this?

    • You can. But this is poor code for extensibility. Consider what would happen if you had a Derived2 that also derived from Base. If you passed in a Derived2, it will tell you it's a base when it's actually a Derived2. That's why if you need to do this kind of class identification, it's generally better to use a virtual function.

  8. Hi Alex,

    In your solution example, I have a doubt. I think friend function does not get inherited, then how does base class operator<<() function gets called?

    • Subclasses don't inherit friend associations (although our operator<&lt is a friend of Base, that operator is not a friend of Derived just because Derived inherits Base).

      But that isn't relevant here. What is relevant here is that an object of type Derived can be trivially upcast to an object of type Base, so there is an version of operator<&lt that can matches our function call to std::cout << d.