Search code examples
c++classinheritanceoperator-overloadingistream

Overload >> in inherited class c++


I've overload the operator << in a inherited class, it's working fine, however when I try to overload the operator >> , it shows lots of errors. What's my mistake?

class Base{
private:
    virtual std::ostream& print(std::ostream&) const = 0;
    virtual std::istream& read(std::istream&);
protected:
    //atributes
public:
    //other functions
    friend std::ostream& operator << (std::ostream& os, const Base& b) {
        return b.print(os);
    }
    friend std::istream& operator >> (std::istream& is, Base& bb) {
        return bb.read(is);
    }
};

class Inherited: public Base{
private:
    //atributes
    std::ostream& print(std::ostream& os) const {
        //things I want to print
    }
    std::istream& read(std::istream& is){
        //things I want to read
        return is;
    }
public:
    //other functions
};

Defining istream as virtual pure (virtual...const = 0;) also doesn't work.


Solution

  • You did not declare read to be pure virtual in Base.

    virtual std::istream& read(std::istream&);
    

    With the above declaration, the compiler/linker expect an implementation of the function in the base class. To fix the problem, make the function a pure virtual function of Base.

    virtual std::istream& read(std::istream&) = 0;
    

    PS Note that it is not a const member function.