Home > database >  How to ensure that inheriting classes are implementing a friend function (ostream)?
How to ensure that inheriting classes are implementing a friend function (ostream)?

Time:09-02

I'd rather implement a non-friend function and directly mark the function as virtual.

But I'm in a situation where I'd like to ensure that a specific set of classes implement an overloading of

friend std::ostream& operator << (std::ostream& os, MyClass& myClass);

and I found no other way to link it directly to my class. (Other possibility of implementation of operator is moving it outside my class, without friend)

Syntax lords, do I have any way of properly implementing this rule ? (having children overriding << ostream operator)

Edit - Related subjects on following threads:

Overloaded stream insertion operator (<<) in the sub-class

virtual insertion operator overloading for base and derived class.

CodePudding user response:

You can create a pure virtual method - that will require inherited classes to overload it, then make friend output operator to call it. For example:

class MyClass {
public:
    virtual ~MyClass();
    virtual void output( std::ostream &os ) const = 0;

    friend std::ostream& operator << (std::ostream& os, const MyClass& myClass)
    {
        myClass.output( os );
        return os;
    }
};
  • Related