overloading std::ostream& operator<< in the derived class without static_cast<>
<p>Is this the only way of overloading the <code>ostream&amp; operator&lt;&lt;</code> for a derived class without duplicating code for the base class? Are the casts not something to be avoided? </p>

<p>I don't see any other way, except to define some kind of function in the base class that will represent the data of the base class as something that std::operator&lt;&lt; could "eat up" (like a string?), doing the same thing for the derived class (calling the base class stream representation function within the derived class stream. rep. function of course). </p>

<p>What is the ideal solution to this problem? </p>

<pre><code>#include &lt;iostream&gt;

class Base
{
    private: 
        int b_;
    public: 
        Base()
            :
                b_()
        {};

        Base (int b)
            : 
                b_(b)
        {};

        friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Base&amp; b);
};

std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, const Base&amp; b)
{
    os &lt;&lt; b.b_; 
    return os;
}

class Derived
:
    public Base
{
    private: 
        int d_;
    public: 
        Derived()
            :
                d_()
        {};

        Derived (int b, int d)
            : 
                Base(b), 
                d_(d)
        {};

        friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Derived&amp; b);
};

std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, const Derived&amp; b)
{
    os &lt;&lt; static_cast&lt;const Base&amp;&gt;(b) &lt;&lt; " " &lt;&lt; b.d_; 
    return os;
}



using namespace std;


int main(int argc, const char *argv[])
{
    Base b(4);

    cout &lt;&lt; b &lt;&lt; endl;

    Derived d(4,5);

    cout &lt;&lt; d &lt;&lt; endl;

    return 0;
}
</code></pre>
