Search code examples
c++class-design

C++: ADT Base class with hard-coded Derived classes vs all-encompassing class built from file-input


Which is a better design: An ADT Base class with hard-coded, concrete derived classes and instances or all-encompassing class whose instances are built from file input?

EXAMPLE:

class ADTSpell {
    ADTSpell(std::string name, int min_damage, int max_damage);
    virtual ~ADTSpell()=0;
    //...
};

class Fire : public ADTSpell {
    Fire() : ADTSpell("Fire", 14, 15) { }
    //...
};

/* Other concrete derived classes */

--OR--

class Spell {
    Spell(std::string name, int min_damage, int max_damage, /*...*/ )
    //...
};

File: Spells.txt
Fire 14 15
Heal -3 -5
Ice 5 8

Solution

  • The KISS (Keep It Simple ) principle would suggest you using just

    struct Spell
    {
       std::string Type;
       int MinDamage;
       int MaxDamage;
    };
    

    The point is simple: you've already generalized all the spells. In principle, they differ only by their name. The parameters (min/max) are easily stored as fields. All of these does not require advanced polymorphism.

    The loading/saving code for these "spells" are not going to be more difficult then the class-based solution.

    If you need more parameters (like the projectile type) it may be still included as a field to this structure.

    More important, if you're going to pass instances of this "classes" over the network or attempt marshaling them to Lua/Python/.NET/whatever, you'll consider changing std::string by char Type[FIXED_SIZE] or even to the int Type (with some enumeration).