Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

People also ask

How do you initialize a constant member variable in a class?

To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.

How do you declare a constant variable?

Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.

How do you declare and initialize a constant in C++?

A constant variable must be initialized at its declaration. To declare a constant variable in C++, the keyword const is written before the variable's data type. Constant variables can be declared for any data types, such as int , double , char , or string .

Can static members be const?

A static data member can be of any type except for void or void qualified with const or volatile. You cannot declare a static data member as mutable.


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??