Saving pointers to file in C++

I'm developing a game for a course at my school. One of the assignments is to enable saving the game to a file and later load the game from the same file.

The problem I'm having are pointers. I'm not allocating anything on the stack (due to ownership of an item for example) so all the classes have pointers to whatever they want a reference to.

While this is quite easy to solve (assign an ID to each object and store that id instead of the pointer) the real problem comes with multiple inheritance.

Let's take the class Actor for example. It looks like this: class Actor : public Object, public ItemOwner where Object is a Obj-C-style base class which has a retain count and release, retain and autorelease methods. ItemOwner is simply an Interface which has some methods such as virtual bool add(Item *item) = 0;, virtual void remove(Item *item) = 0; and virtual bool transfer_ownership(Item *item, ItemOwner *new_owner) = 0;

Now the real question comes, which class(es?) should have ID's. And Item has a pointer to an ItemOwner while a Room has a pointer to an Actor. The actor should only be saved once.

I've thought about assigning ID's to each superclass (Object, ItemOwner, etc) but if I have a pointer to an Actor will that actor always have the same adress as the Object it contains (Actor *foo = new Actor(); foo == (Object *)foo)? If not every single class in the game will need to have an ID.

Any thoughts or suggestions would be greatly appreciated.

Answers


By using UIDs, you create a mapping:

serialized_object -> UID -> deserialized_object.

Why bothering? You already have UIDs, and these are pointers to objects. By using this mapping:

&serialized_object -> &deserialized_object

you drop a level of indirection, UIDs as created automatically, and all you have to do is to deduce this mapping in deserealization process.

The simpliest way is to serialize the objects with all the pointers as is, and to store together with each object its address. This will also help you check if an object was serialized alraedy.

While serialization would be simple, deserialization will have its tricks. You'll have to be carefull to update each old pointer (remember? they contained adresses that are no more valid) with the correct object address.


Need Your Help

Can you use ANY SQLITE3 database in iOS, or is there a special format you should match?

ios ruby-on-rails sqlite3

Specifically, it would be nice to be able to use a database I already have that Rails 3 generated and just stick it straight into iOS. Would that be possible?

Date as folder name

c# datetime folder filenames

Fast one, why this code isnt working for me:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.