Place to declare constants.



  • Hello,

    My name is Mario, I'm new to this forum
    and I sincerely apologize for my bad English.

    I am having a dilemma about which is the best place to declare constants.
    For example, I have an item that is derived from QGraphicsItem,
    this element has two constant colors: pen color and brush color.

    I'm thinking of declaring them as private constants:
    @
    class Rect : public QGraphicsItem
    {
    ....
    private:
    static const int _penColor = 0;
    static const int _brushColor = 1;
    };
    @

    But it also can be declared as definitions in the header:
    @
    #define PENCOLOR 0
    #define BRUSHCOLOR 1
    @

    As well as local variables:
    @
    void Rect::draw()
    {
    const int penColor = 0;
    const int brushColor = 1;
    }
    @

    Maybe this is not important, but I wish I know what you think?

    Thanks, Mariø.



  • Hello.
    The best way is using of private non static constant members. Also, if you want be able to change these parameters during app running then you'd better declare them non constant.
    The members should be non static because it'll be better for derived classes.
    Also you may declare these members as properties.



  • Hello.
    Avoid using of #define declarations, because it's preprocessors constant and makes your program hard to debug.
    For compile-time constant in class you can use unnamed enum.
    @
    class Rect : public QGraphicsItem
    {
    ....
    private:
    enum {
    kPenColor = 0,
    kBrushColor = 1
    };
    };

    @



  • Thinking OOP: Is a good idea to declare these members as properties even when I don't want to change these values?....Not sarcasm is a real question xP



  • Hello.
    It's a good idea if changing of these values doesn't argue with those semantics. I mean, if these are real colors used for drawing, then it's all right to make them properties, but if these are just a kind of constants for compile time (like preprocessor definitions), then it's wrong to make them properties.
    And of cause if you don't ever want to change these values, then don't declare them as properties.



  • [quote author="Wilk" date="1337136378"]If these are real colors used for drawing, then it’s all right to make them properties.[/quote]
    Yes, these are real colors. I mean objects.

    [quote author="Wilk" date="1337136378"]
    And of cause if you don’t ever want to change these values, then don’t declare them as properties.
    Yes, I don't want to change these values.[/quote]

    Probably I will use local variables as constants:
    @
    void Rect::draw()
    {
    const QColor penColor();
    const QColor brushColor();
    }
    @

    @Serg Thanks for this tip:

    [quote author="" date="1337058161"]For compile-time constant in class you can use unnamed enum.[/quote]


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.