Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing polymorphic class data to a file?

So I have these classes. There's one base class, but it has/will have lots and lots of derivatives, and those derivative classes will be able to have derivatives as well. I'd like to be able to have a function that writes their binary data to a file, but I'm not sure how to do this with lots and lots of derived classes.

I was thinking something along the lines of:

void writeData(ofstream & _fstream)
{
    _fstream.write()//etc..
}

But then each derived class that implemented this method would have to write all of it's parent class's data, and that would be duplicating a lot of code.

What's the best way to do this without rewriting all of the previously written writeData() code?

like image 652
lowq Avatar asked Dec 10 '22 04:12

lowq


1 Answers

You can call the base class implementation from the derived class implementation:

void Derived::writeData(ofstream & _fstream)
{
    // Base class writes its data
    Base::writeData(_fstream);

    // now I can write the data that is specific to this Derived class
    _fstream.write()//etc..
}
like image 69
filipe Avatar answered Dec 27 '22 15:12

filipe