I think there is no direct way to remove this overhead. This is usually done in two ways. First of all, an object needs a serialization mechanism:
To serialize things, you need a place to serialize. In this case, we will do this using a data container, but it can also be a file stream or a container class. Serialization can be performed inside the object or from the outside, the simplest implementation now occurs from the inside:
The simple part of serialization:
class Shape{ public: virtual void serialize( Datacontainer &o ) const = 0; }; class Triangle: public Shape{ void serialize( Datacontainer &o ) const{ o.add('T'); o.add(corners); } std::vector<point> corners; } class Circle: public Shape{ void serialize( Datacontainer &o ) const{ o.add('C'); o.add(center); o.add(radius); } point center; double radius; }
During serialization, you can do this using the base Shape class:
Shape *tri = new Triangle; tri->serialize( dataContainer or file );
Deserialization is not so simple because you need to know the type. A good example for this is the Builder pattern. Despite this, we can implement a more likely C ++ method:
Add the following to all your classes:
static Shape* createFrom( Datacontainer &o );
For example, the implementation of Circle:
Shape* Circle::createFrom( Datacontainer &o ) { Circle *c = new Circle() c->center = o.get(); c->radius = o.get(); }
This allows us to create a specific instance, but we have a common functional trace for the method. Now you can implement a very simple builder like this:
class ShapeBuilder { public: static Shape* createShape( Datacontainer& o ) { char id = o.get(); swith(id){ case 'T': return Triangle::createFrom(o); case 'C': return Circle::createFrom(o); } } }