samedi 11 mars 2017

inheritance just to share enum - dangerous?

Whenever I want to share an enum among many files I will :-

  • create a class e.g. B dedicated to the enum
  • a class, which want to access to the enum easily, will derived from B

Mostly, there will be one class for one enum. (1:1)

class B{
    public: enum EnumB{ E1,E2 };  
};
class C : public B{ /* .... access EnumB */}; //a kind of struct
class D : public B{ /* .... access EnumB */}; //a kind of widget/manager

This approach enables C and D to access E1 without any prefix B.

I think it is OK, because I use those enum in a very-narrow scope. (2-4 classes)
A SO post also states it is OK to use inheritance for utility.

However, I don't find that it is a popular approach :-

Question

  • How my approach is dangerous? What is its disadvantages?

    In real case, I tend to multi-inheritance many classes just for that.

    class ShadowEnum{ public: enum ShadowE{ SHADOW,NO_SHADOW};   };
    class ColorEnum{  public: enum ColorE{ RED,BLUE,GREEN,PURPLE };  
    class LightType{  public: enum LightE{ L_SPHERE, L_CONE, L_SPOT};   };   
    class LightManager : public ShadowEnum, public ColorEnum,public LightType{
         /* some code */
    };
    
    
  • Can it be a cause of a dread-diamond issue in future?

By the way, I think enum-class is not in the scope of this question.

Aucun commentaire:

Enregistrer un commentaire