Good time of day. When planning a term paper, I began to determine what functions would be contained in my software. I have two similar objects (Doctor, Patient), the fields of these objects are about the same, and here I sit, I think to realize a common function of writing the structure to a file, but if everything is implemented in one function, then it seems to me that the function will be very large it is better to do two functions, one records the structure of the patients, and the second records the doctor. how to do it better? What advice can you give?

  • Well, if you have objects there - make WriteToFile method for objects - Vladimir Martyanov
  • my personal opinion is that either use a universal serialization mechanism (find a good library or just binary the entire structure) or each structure has its own method for writing itself to a file. - pavel

2 answers 2

It is unlikely that the Доктор and the Пациент will be the heirs of a common class (unless the Человек can be such). But if they really have a lot in common, then it may make sense to pick out a common ancestor with a virtual member function to write to; respectively. for descendant classes, virtual functions will write specific information. Making one non-member function to write two different structures (apparently with an if-else or switch ), in my opinion, the solution is not optimal.

The problem is only in the correct reading from the file - there should be a dispatcher who, when reading, should correctly call the function of the corresponding class (this is the second question, however).

For a course project, I think, there is no particular reason to resort to external libraries. Writing such a simple one of yours will take no more time than learning a stranger, but you will get priceless bumps on your head :), referred to as experience ...

    The answer often depends on the approach chosen.

    In the simplest case, you can select the base class with the virtual functions serialize and deserialize , which allow you to save and load an element, respectively, using the selected format (byte representation, json, xml, etc.). I would not load this class with the function of writing to a file, because a separate class must deal with this.

    After some time, you will encounter a situation in which you have to make changes to your structures. In addition, you will have to additionally support previously serialized data into files.

    You can, of course, implement various versioning mechanisms as an educational task, but it will be much easier to use a ready-made library implementation for data serialization, for example, Boost Serialization