Suppose we have a complex (i.e. non-primitive) class ComplexObject
defined below:
class A{...};
class B{...};
class C{...};
class ComplexObject
{
private:
A _fieldA;
B _fieldB;
C _fieldC;
};
I would like to implement a serializer that serializes instances of ComplexObject
into binary form. From my experience in C#, I have seen essentially 3 distinct ways to implement a serializer.
- Define a
serialize(binarystream&)
method inComplexObject
's definition and those of the "child" classes,A
,B
, andC
. Theserialize
method defined inComplexObject
will recursively call those of the child members. - Create a separate class that contains methods to serialize each of
ComplexObject
,A
,B
, andC
. The method used to serializeComplexObject
will recursively call those of the child members. Of course, getters will have to be defined in the classes to retrieve private fields for the serializer. - Use reflection to generate a template of the object and to write all serializable fields into a table according to the generated template.
Unfortunately I believe reflection will be extremely hard to utilize in C++, so I shall stay away from the third option. I have seen options 1 and 2 both been used very often (in C#).
An advantage that option 1 possess over option 2 is that it allows for classes that derive from ComplexObject
, by marking the serilalize(binarystream&)
method virtual. However, it would add to the list of member functions of an object and confuse programmers. You don't see a serialize
method being defined in std::string
, do you?
On the other hand, option 2 takes out and groups all serialization methods together to make things a bit neater. However, I suppose it isn't as easy to accommodate for derived classes of ComplexObject
.
Under which circumstances should each of the options (1 and 2) be used?