How to declare a static constant member variable of a class that involves some simple calculations?

22,323

In C++11 you could use constexpr:

class box
{
    public:
        box();
    private:
        static constexpr double height = 10.0;
        static constexpr double lid_height = 0.5 + height;
};

Otherwise, you could use an inline function (but you need use call it as box::lid_height()), which a good optimizer should be able to reduce it to a constant on use:

class box
{
    public:
        box();
    private:
        static const double height = 10.0;
        static double lid_height() { return 0.5 + height; }
};
Share:
22,323
tuzzer
Author by

tuzzer

Updated on July 09, 2022

Comments

  • tuzzer
    tuzzer almost 2 years

    I tried to have one static const member variable to relate to another static const variable in a class. The motivation is that if I need to modify one value later (when coding), i don't need to change all of those that are related to each other one by one.

    For example:

    class Box
    {
        public:
            Box();
        private:
            static const double height = 10.0;
            static const double lid_height = 0.5 + height;
    };
    

    It won't compile and the error was ''Box::height' cannot appear in a constant-expression'. So I guess you must type in the value of a static const member. But is there a way to have one member relate to another member variable of the same class, given that they will all be static const??

  • tuzzer
    tuzzer about 12 years
    Thanks! This would be a nice work around but I think it is a bit inconvenient to have to call a function.