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 ?
Non-static data members are the variables that are declared in a member specification of a class.
Non-static data members may be initialized in one of two ways: 1) In the member initializer list of the constructor.
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.
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.
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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With