简体   繁体   中英

c++ Writing to Binary files from multiple inheritance class

I have a case similar to "The diamond of death"

I have class B and C which Virtually Inherit Class A, and also Class D which Inherit Classes B and C.

  A  
 / \  
B   C  
 \ /  
  D 

B & C has inherited members, and also their own members. D has only inherited members.

I'm writing Save method which gets ofstream and should write the Object to a binary file.

And a Load method which gets ifstream and should create the object from a binary file.

The Method are virtual and written in such a way that each class Method handles only that specific class members Load & Save (and uses the inherited classes methods for the rest of the inherited members)

Now when writing the Save method for D, basically I only need to do:

B.save();
C.save();

Obviously this will cause A.save() to be called twice which will cause A to be written to the file twice

I think something like add a saveOnly method to B and C which will save only their members (and not A's) is silly

So I wonder what is the Best Practices for such a case ?

The best practice is to not make diamonds in your class inheritance. That will always cause issues and is best avoided. Evaluate each link in the inheritance and think about whether you could do something different, such as using composition at some point or making the base class a pure virtual interface instead.

If you really want to keep that inheritance, then instead of making A::save() a virtual method, make a protected pure virtual A::onSave() method instead that is expected to be overridden in each derived class. A::save() will do what it needs to do, then call onSave() . B and C will both implement onSave() and do what they need to do, but will not call A::onSave() (because it is pure virtual). D will implement onSave() and will call B::onSave() and C::onSave() . This works around the issue for this case, but you will always run into more issues like this if you make inheritance diamonds like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM