constant class variable

Is this declaration legal in a class header file (with it's missing an initial value)?

const unsigned int maxusers_;

If not, I need a variable that will be initialized through the constructor, but will be not be changed during the life of the object (thus const) and will be used by other class members. (implementation will be in a separate .cpp file)

How is this done correctly? Thanks.
That's perfectly legal. It just needs to be initialized in the member initialization list of your constructors.
Well it is but you have to provide initialisation of maxusers_ in the initializer list of the constrcutor, maybe something like:

MyClass() : maxusers_(0) {};
MyClass(int maxusers) : maxusers_(maxusers) {};

You cannot assign a value to maxusers_ otherwise as it is constant.
Last edited on
Great, thanks!
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
Last edited on
Topic archived. No new replies allowed.