in-class initialization

H

Hunter Hou

Folks,

If a member variable is initialized in class, it must be static and
const. I know this and regard it as a convention. But who knows why
standard define this? What's the advangtage or otherwise shortcomings?

For example,

class C {

const int a = 0;
static int a = 0;

// Must be like this:

static const int a = 0;

// or as an enum
};


Thanks,
Hunter
 
T

tom_usenet

Folks,

If a member variable is initialized in class, it must be static and
const. I know this and regard it as a convention. But who knows why
standard define this?

Integral const expressions are a special case - they can be used as
template parameters, array bounds, etc. No other const type has this
special aspect - there's nothing you can do with a const float with a
known compile time value (such as a float literal, 5.0) that you can't
do with one where the value is known only at runtime. So it is
potentially useful for static integral const members of classes to be
integral const expressions, and for this they have to be defined
inside the class definition.

As for static, what is the purpose of a non static const that you
initialize in the class declaration? All instances will have the same
value for that variable, so it may as well be static.

Tom
 
D

demps

Hunter Hou said:
Folks,

If a member variable is initialized in class, it must be static and
const. I know this and regard it as a convention. But who knows why
standard define this? What's the advangtage or otherwise shortcomings?

For example,

class C {

const int a = 0;
This can't be used because you cannont initialise members in the class
definition. The best place for this is in the initialisation list of
the class constructor eg:
C:C () : a(0)
{}
static int a = 0;
This won't work because each time the class is insantiated the
definition is reference, however if "a" is static ie global across
instances of that class then it may be changed somewhere else by
another instance rendering such an initialisation upon each reference
invalid.
// Must be like this:

static const int a = 0;
This works because it is a static const, "a" will be instantiated
(before even the class is instantiated unless that is static also)
just once and will not change across instances of the class and will
always be 0
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,164
Messages
2,570,898
Members
47,439
Latest member
shasuze

Latest Threads

Top