Advertisement

Saving Classes

Started by December 20, 2000 12:38 AM
5 comments, last by vbisme 24 years ago
  
class MyClass
{
int myInt;
int myInt2;
int abc;
int cef;
};
  
Let''s say I saved this to a disk file...Would the first 4 bytes be myInt, the next be myInt2 and so on. Is the order of saving goes as the class is declared or what?
Yes.
Advertisement
But don''t, as you''ll be saving your structure padding as well. This would make your data files non-portable. Read and write each member one at a time. A pain, I know, but it''s the Right Thing To Do.
I don''t know if this applies to your situation, but you should take care with this if you also want to add member functions to your classes. For cases like that, I use a serialize/deserialize paradigm, sort of like this:

class Serializable{public:  Serializable(FileStream *f);  virtual void serialize(FileStream f);}; 


Then I derive classes from this, overriding the constructor and the serialize() function. The constructor is used to load the object''s members from a file ("deserialize"), whereas the serialize() function saves these members to a file. As FordPrefect already mentioned, you should read/write your members one by one, not all at a time.

- Tom
You can''t excpect that the data members is in the same order as they are defined in the class either. C++ usally keeps public, protected and public variables grouped togheter in memory.
Ins''t it better to make a method "save" or something so that you can save one by one in your desired order?
import money.*;#include "cas.h"uses bucks;
Advertisement
You should save the values one by one, if you had a virtual class or a class inhereted from a virtual class and did something like :

saveClass(&myClass, sizeof(myClass));

You would save the vtable, and that would almost definitly create problems when loading (at least in Release build).

This topic is closed to new replies.

Advertisement