Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of non-static const data member? [duplicate]

For the following code:

class A
{
public:
    const int cx = 5;
};

Here, an instance of cx will be created for every object of A. Which seems a waste to me, as cx can never be modified. Actually, I don't see any reason why compiler shouldn't enforce making a const data member static. Can anybody please explain this to me ?

like image 256
Sam Avatar asked Nov 03 '14 17:11

Sam


People also ask

What is non-static data member?

Non-static data members are the variables that are declared in a member specification of a class.

Where can a non-static reference member variable of a class be initialized?

Non-static data members may be initialized in one of two ways: 1) In the member initializer list of the constructor.

What is the purpose of const in c++?

The const keyword specifies that a variable's value is constant and tells the compiler to prevent the programmer from modifying it. In C, constant values default to external linkage, so they can appear only in source files.

What is NSDMI?

NSDMI - Non-static data member initialization. In short, the compiler performs the initialization of your fields as you'd write it in the constructor initializer list.


2 Answers

A const data member does not have to be the same for all instances. You can initialize it in the constructor.

class A
{
public:
    A(int n) :cx(n) {}

    const int cx;
};

int main()
{
    A a1(10);
    A a2(100);
}
like image 174
Benjamin Lindley Avatar answered Sep 18 '22 13:09

Benjamin Lindley


Actually, I don't see any reason why compiler shouldn't enforce making a const data member static.

Have you considered that cx might be initialized in the constructor with a value known at run-time - and varying between different instances of A?
const members make assignment to them impossible, but sometimes having a member that cannot change its initial value proves useful.

Definitely not the best example, but to illustrate the idea:

struct Multiplier
{
    const int factor;

    Multiplier(int factor) : factor(factor) {}

    int operator()( int val ) const
    {
        return val * factor;
    }
};

std::vector<int> vec{1, 2, 3};
std::vector<int> vec2;

int i;
std::cin >> i;

std::transform( std::begin(vec), std::end(vec),
                std::back_inserter(vec2), Multiplier(i) );

// vec2 contains multiples of the values of vec
like image 40
Columbo Avatar answered Sep 18 '22 13:09

Columbo