How can I serialize an derived type pointer to interface type object in c++?

49 Views Asked by At

Interface * base_ptr1 = new Derived1();

Interface * base_ptr2 = new Derived2();

In theory I should have serialize() method in all classes but my interface type class does not have data members, only abstract virtual methods.

1

There are 1 best solutions below

0
Ted Lyngmo On

You could add pure virtual functions to do the serialization.

class Interface {
public:
    virtual void read(std::istream& is) = 0;
    virtual void write(std::ostream& os) const = 0;
};

std::istream& operator>>(std::istream& is, Interface& i) {
    i.read(is);
    return is;
}

std::ostream& operator<<(std::ostream& os, const Interface& i) {
    i.write(os);
    return os;
}

Now, the concrete classes only needs to implement read and write and the streaming operators implemented for Interface will work for them all.