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) { }
}

      

The class 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 class b statements, is there a way to read and write common fields using class a I / O statements? Thank.

+3


source to share


2 answers


You can reuse the operator by choosing ob

in the superclass type:



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;
}

      

+2


source


Keep extractor and insert overloading for the base class, and defer the actual operation to the 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 power 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
    }
};

      

+1


source







All Articles