Home > database >  C class Design with Inheritance
C class Design with Inheritance

Time:09-18

class Base 
{
public:
    static int  GetType_S()
    {
        return 1;
    }
    virtual int GetType()
    {
        return GetType_S();
    }
};

class Son1 : public Base 
{
public:
    static int GetType_S()
    {
        return 2;
    }
    virtual int GetType()
    {
        return GetType_S();
    }
};

My Question is : When I need some other classes like "Son1,Son2..." ,every class should implement GetType and GetType_S function, This two functions is repeated.So How to design this classes gracefully to let son classes implement only one function?And It is best not to use macros.

CodePudding user response:

You can have a class template that each SonN inherits from, which in turn inherits Base.

template <int Type>
class Middle : public Base 
{
public:
    static int  GetType_S()
    {
        return Type;
    }
    virtual int GetType()
    {
        return GetType_S();
    }
};

class Son1 : public Middle<2> {};

class Son2 : public Middle<3> {};

class Whatever : public Middle<42> {}; 

Or, if there is nothing else in those classes:

using Son1 = Middle<2>;
using Son2 = Middle<3>;
using Whatever = Middle<42>;
  • Related