0

I have a problem with serialisation using the Marmalade SDK. I understand the principles like serialising primitives but what about polymorphic objects?

According to the Marmalade examples you serialise objects like so:

void Serialise()
{
    uint8 isObject;

    if (IwSerialiseIsWriting())
    // writing
    {
        // record whether m_Happy exists
        isObject = m_Happy ? 1 : 0;
        IwSerialiseUInt8(isObject);

        // serialise out m_Happy if it exists
        if (m_Happy)
            m_Happy->Serialise();
    }
    else
    // reading
    {
        IwSerialiseUInt8(isObject);

        // if an object was written out then read it in
        if (isObject)
        {
            // if m_Happy already exists then delete it
            if (m_Happy)
                delete m_Happy;

            m_Happy = new CHappy;

            // serialise in m_Happy
            m_Happy->Serialise();
        }
    }
}

My question is how can you use this method when you have a polymorphic type? For example:

I have an object:

AbstractClass *object;

When serialising, how can I initiate this object correctly? According to the simple Marmalade example I would:

// reading
if(objectExists) {
    object = new AbstractClass(); // uh oh
}
Binary Pulsar
  • 1,209
  • 10
  • 17

1 Answers1

0

to use that you need to call new on one of the concrete subclass. For example -

//Writing - 
AbstractClass *object = new ConcreteClass();
object->Serialise();

Where ConcreteClass is the concrete subclass of AbstractClass. Theoritically you shouldn't be having an object of just the Abstract class, unless using polymorphism.

The same code applies to when you are reading from the serialization file. Just as a tip, you need to deserialise objects/primitives in the same order you have serialised them.

0xC0DED00D
  • 19,522
  • 20
  • 117
  • 184
  • I understand that but I don't know what that concrete class will be at runtime, that's my problem. When reading, the object will not have been created yet. I need to create it (by knowing which concrete class it was when it was serialised) and then call `object->Serialise()` – Binary Pulsar Oct 09 '13 at 05:16
  • The easy solution would be to have a separate string variable or enum in the serialization file, just before the actual serialized object, which stores the name of the concrete class. When deserializing you can identify which class is it's concrete class and can initialize the object accordingly. – 0xC0DED00D Oct 09 '13 at 11:13
  • That sounds like I would need a factory class (or similar) that would have to be updated every time I subclassed `AbstractClass` which wouldn't really be practical. Or am I missing something? – Binary Pulsar Oct 09 '13 at 11:27
  • Factory class seems to be a solution. Your problem is not specific to marmalade. It's a C++ problem. You need to check if there's any solution already available. I'll update if I find any. – 0xC0DED00D Oct 09 '13 at 11:57