Search code examples
c++classoperator-overloadingvirtualfunction-definition

Virtual overloaded operators >> and <<


I need an interface that would require its subclasses to overload << and >>, but I'm not quite sure how since these operators aren't overloaded as member functions:

std::istream& operator>> (std::istream& in, Student& student) {
    in >> student.name >> student.group;
    for (int& i : student.marks) { in >> i; }
    return in;
} 

Maybe there's a way to make it a member function?


Solution

  • You could do something like this:

    class StudentInterface
    {
    public:
        virtual void readSelfFrom(std::istream& in) = 0;
    };
    
    std::istream& operator>> (std::istream& in, StudentInteface& student) 
    {
        student.readSelfFrom(in);
        return in;
    } 
    

    And then let users derive from StudentInterface, eg:

    class Student: public StudentInterface
    {
    public:
        void readSelfFrom(std::istream& in) override
        {
            in >> name >> group;
            for (int& i : marks) { in >> i; }
        }
    };