c++polymorphismabstract-classstream-operators

Operator << in abstract classes, c++


If I have an abstract class, let's call it "Vertebrate", it has a field std::string name; and it has a pure virtual method virtual void print(std::ostream&) const noexcept = 0; which will be overridden in child classes and called in operator<<.

I get how polymorphism works, and how to implement the operator<< in inherited classes.

What I don't get:

I don't get this: how to implement an operator<< in that abstract class, that uses the virtual print function. Why this code does not work? My abstract class needs to have operator<<.

virtual void print(std::ostream&) const noexcept = 0;
std::ostream & operator<<(std::ostream & str, Member &obj)
{
    return obj.print(str);
}

That is the abstract class code.


Solution

  • You are trying to return the result of print which is void, but operator<< should return std::ostream.

    The following should work:

    class Vertebrate
    {
        // ...
        virtual void print(std::ostream&) const noexcept = 0;
    };
    
    std::ostream& operator<<(std::ostream& stream, Vertebrate& obj)
    {
        obj.print(stream);
        return stream;
    }