Shury
Shury

Reputation: 578

Istream and ostream in inheritance

I have two classes:

class a{
    friend istream &operator>> (istream&in, a&ob) { }
    friend ostream &operator<< (ostream&out, const a&ob) { }
}

class b:public a{
    friend istream &operator>> (istream&in, b&ob) { }
    friend ostream &operator<< (ostream&out, const b&ob) { }
}

Class a works great. I can read and write objects of type a. Class b inherits everything from class a and adds some new data. In my istream and ostream operators of class b is there a way to read and write the common fields using the input/output operators of class a? Thank you.

Upvotes: 3

Views: 759

Answers (2)

David G
David G

Reputation: 96810

Keep the extractor and inserter overloads for the base class, and defer the actual operation to a virtual member function:

istream& operator>>(istream& in, a& ob)
{
    ob.read(in);
    return in;
}

ostream& operator<<(ostream& out, const a& ob)
{
    ob.write(out);
    return out;
}

The overrider for b can simply call the base class overload:

class b : public a {
public:
    void read(std::istream& is) {
        a::read(is);
        // read into derived class
    }

    void write(std::ostream& os) {
        a::write(os);
        // write out derived class
    }
};

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

You can reuse the operator by casting ob to the type of superclass:

ostream &operator<< (ostream& out, const b& ob) {
   // Output the parts common to a and b
   out << static_cast<const a&>(ob);
   // Do additional things specific to b
   out << some_part_specific_to_b;
   return out;
}

Upvotes: 2

Related Questions