Where should I store a list of objects?

I have a base class and two derived classes. I want to write and read objects of these classes to / from a file. I was thinking about virtual functions to write/read data, but I don't know where should I place these functions. In the base class? When I will be reading data from the file I will store pointers to objects in a vector, but I suppose I cannot have a vector of pointers to objects of a class in which this vector is declared. Could someone help me solve this problem? Thanks in advance for any advice.

2 answers

  • answered 2018-04-17 05:57 Stephan Lechner

    When you write the objects to the file, you also have to store some information such that you know the type/class of the object when reading it in again later; Otherwise you will not know which of the derived classes to instantiate.

    Once you have solved this, you can decide to store the objects where ever and in which way you want.

  • answered 2018-04-17 06:16 M. Denninger

    As far as I understand your problem, you have a base class and two derived classes. All of them you want to write and read from a file and you want to read more than one instance from this object at a time.

    In my opinion you need a container class, which takes care of the reading and writing. This means you implement a class, which stores your instances in a vector and then can save them to the disk and read them again.

    Saving different types of classes, which are inherited from the same base class, requires additionally that you add a type, which you have to check during the writing and the reading, to process the stored information correctly.