3

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?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Martian
  • 227
  • 1
  • 15
  • 2
    Declare a member virtual function for example like virtual std::ostream & out( std::ostream &os = std::cout ) const; And call it inside the body of the overloaded operator <<. – Vlad from Moscow Jun 01 '20 at 21:11

2 Answers2

10

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; }
    }
};
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Jeffrey
  • 11,063
  • 1
  • 21
  • 42
5

A general approach in such a case is to declare in the base class a virtual member function like

virtual std::ostream & out( std::ostream &os = std::cout ) const;

In derived classes the function will be overriden.

Then the operator << can look like

std::ostream & operator <<( std::ostream &os, const Base &obj )
{
    return obj.out( os );
}

A similar way can be defined the operator >> only in this case the virtual member function will not be constant..

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335