Search code examples
c++inheritanceoperator-overloadingpure-virtual

Overloading operator << in derived class


Say I have two classes, one of which is abstract and one of which is a real, derived child of the other. Both of them are overloading the operator << function. How can I call the abstract class' operator from within the derived class' overloaded function?

The set up:

class Parent {
    virtual void open() = 0;
    friend std::ostream& operator << (std::ostream& out, const Parent& instance);
};

class Derived : public Parent {
    void open();
    friend std::ostream& operator << (std::ostream& out, const Derived& instance);
};

std::ostream& operator << (std::ostream& out, const Derived& instance) {
    out << "derived ";
    out << instance; // how can I call the function in the parent class here?
}

I've tried statically casting the instance to the parent class, but you obviously can't because it's an abstract class and cannot be instantiated. out << static_cast<Parent>(instance); says "error: a cast to abstract class 'Parent' is not allowed."

I've also tried calling Parent::operator<<(out, instance), but because it's a friend function it is not technically a member function of Parent.

So I'm out of ideas... Does anyone know if this can be done? And what the syntax for calling this function is? Cheers.


Solution

  • This is where you need a type conversion.

    std::ostream& operator << (std::ostream& out, const Derived& instance)
    {
         out << "derived ";
         out << (const Parent &)instance;    // Alternative 1: C style cast
         out << static_cast<const Parent &>(instance);   // Alternative 2
         return out;
    }