I don't think this method does what you're expecting.
Yes this makes the value constant, but does not make it static. That is,
each instance of 'MyClass' will have it's own 'maxusers_' constant. You will not have one constant shared by all of them.
If you want all objects to share a single constant -- then it gets tricky. You need a single instance of the variable for each class. The normal approach to this is to make it static, however
static const
demands that the represented value be supplied immediately (ie: you can't supply it in the ctor like you're doing with
const
)
The workaround is to keep a nonstatic reference to a const var in the class, and call a
function which returns a static const.
Confusing? yes. Here's an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
class MyClass
{
protected:
// the member vars
const unsigned& maxusers; // note it's a const reference, but not static
// the initing function
static const unsigned& InitMaxUsers(unsigned v) // call this function to init your reference
{
static const unsigned realmaxusers = v; // make a static const object local to this function
return realmaxusers; // and return it by reference
}
public:
// example ctor
MyClass(unsigned max)
: maxusers( InitMaxUsers(max) ) // initialize maxusers by calling the static init funciton
{
}
};
|
The difference between these methods can be verified:
1 2 3 4 5 6 7 8
|
int main()
{
// assume MyClass::print simply prints 'maxusers'
MyClass a(1); a.print();
MyClass b(2); b.print();
return 0;
}
|
With the simplistic non-static const approach mentioned previously in this thread, the above will output "1 2", whereas my approach here will output "1 1".
EDIT:
Crap -- although now that I reread your original post I might've misunderstood -- and what was previously described might in fact be exactly what you want.
Oh well XD