Search code examples
c++c++11pointersqdatastream

How to initialize a child class from a pointer on its abstract mother class?


So I'm new to C++, and my problem is this one: I have an abstract class, which as multiple child classes (and they had other child classes too). I am trying to use polymorphism to serialize and deserialize these child classes, and have, in my abstract class:

    virtual QDataStream& serialize(QDataStream& stream)=0;
    virtual QDataStream& deserialize(QDataStream &stream)=0;

So my question is simple: when I deserialize, I want to call the deserialize function, and I do not know yet which child class I am retrieving.

The function goes like this:

QDataStream& operator>>(QDataStream& in, SomeClass& i){

    std::shared_ptr<AbstractClass> ptr;
    ptr->deserialize(in); //Raises an SIGSEGV error

}

I don't know if I'm entirely clear, but basically what I'm trying to do is to instantiate and call whichever child class the stream corresponds to, and call deserialize on it. Is it possible ?

Thanks!

Edit: My first approach which works was to also feed the QDataStream my child class name, so that I know which class to instantiate:

        QString myClassName;
        in >> myClassName;
        if(myClassName == "ChildClass1"){
            std::unique_ptr<AbstractClass> ptr(new ChildClass1);
            ptr->deserialize(in);
        }

But I feel this is really not a clean OOP way!


Solution

  • It is unfortunately not possible to initialize a child class from the base class only. When serialising you will have to serialise some sort of id for the child class. Next when deserializing I suggest you use the factory pattern. Using a factory you pass the id and class data you wish to deserialize. That factory function will construct the required child class and return a pointer to the base class.