Qt World Summit: Submit your Presentation

[SOLVED] How to deserialize derived class in Qt

  • Hi everyone, I have a problem with serialize/deserialize some Shape objects in my project, with serialize, I come up with a solution quite satisfied, using virtual method:

    enum ShapeType{CIRCLE, SQUARE, QUAD};

    class Shape(){
    Shape(const QVector2D &pos):m_pos(pos){}
    void serialize(QDataStream &stream){
    stream << type() << m_pos;

    virtual ShapeType type()=0;
    virtual void doSerialize(QDataStream &stream){}

    QVector2D m_pos;

    QDataStream& operator<<(QDataStream &stream, const Shape &shape){
    return stream;

    class Circle: public Shape{
    Circle(QVector2D pos, float radius):Shape(pos), m_radius(radius){}

    virtual ShapeType type(){return CIRCLE;}
    virtual void doSerialize(QDataStream &stream){

    float m_radius;

    But when deserializing, I have to use this switch statement to create the derived object:
    Shape *deserialize(QDataStream &stream){
    ShapeType type;
    stream >> type;
    QVector2D pos;
    stream >> pos;
    case CIRCLE:
    float radius;
    stream >> radius;
    return new Circle(pos, radius);
    return 0;

    I heard that the above switch statement is antipattern and cumbersome under maintaining, so how to eliminate the switch statement to create object which doesn't need the type() to specify derived class?
    Is there any Qt's way about this?

    Any suggestion would be appreciated.

  • That seems like a classic case for the "factory pattern":http://www.oodesign.com/factory-pattern.html

    Basically you register a factory object for each possible type somewhere during the setup of your application. When you want to deserialize you get the type from the stream, ask each factory which one can produce objects of that type and then have the factory create an object for you from the stream.

  • Thanks Tobias Hunger for your help, the factory pattern seems to be the right solution.

Log in to reply