mercredi 2 mars 2022

Pattern for inheriting and using a member variable in derived classes without casting each time

I have a base class:

class Base{
protected:
    Storage* _storage;

    virtual void createStorage(){
        delete storage;
        _storage = new Storage();
    }

    void exampleUseOfBaseStorage(){
        _storage->baseData++; //some complex calculation
    }
}

struct Storage{
    int baseData;
}

Each derived class has their own kind of storage:

struct DerivedStorage : Storage{
    int derivedData;
}

In the derived class,

class Derived{
protected:
    virtual void createStorage() override{
        delete storage;
        _storage = new DerivedStorage();
    }
}

Hence _storage can be used for all the base class members and the derived class members. The downside is, because for each derived class, I would have to cast the type of storage to DerivedStorage, or whatever type of storage the derived class uses, it is very tedious to type out the cast statement each time. Is there an elegant way around it ?

My solution is to just have one more variable of type DerivedStorage, and just use that in the derived classes member functions. Eg:

class Derived{
protected:
    DerivedStorage* _ds = nullptr;

    virtual void createStorage() override{
        delete storage;
        _storage = new DerivedStorage();
        _ds = _storage; // Use _ds in all member functions of Derived instead of _storage
    }

    void exampleUseOfDerivedStorage(){
         _ds->derivedData++; //some complex calculation
    }
}

Is there a more elegant pattern to use for this use case?

Aucun commentaire:

Enregistrer un commentaire