Archived

This topic is now archived and is closed to further replies.

PHRICTION

const member vars in a class?

Recommended Posts

You certainly can (though it''s not really a variable, then ...); IIRC, you can still initialise it in the constructor''s initialiser list.

Share this post


Link to post
Share on other sites
hmm, wouldn''t you initialize a constant the normal way? in other words,

class xyz {
...
const int t = 1;
...
};

Share this post


Link to post
Share on other sites
You must initialize it like you do static member data.

EG:

// In header
class A { const int x; }


// In source
int A::x = 0; // or any initialization value

Share this post


Link to post
Share on other sites
C-Junkie wrote
hmm, wouldn't you initialize a constant the normal way? in other words,

class xyz {
...
const int t = 1;
...
};
"

some compilers will allow you to do that, but Visual Studio will not (I am not sure what the current standard says about it). For those that do not allow it, you have to declare it const in the class defintion, and assign the value in the constructor's initializer list

class xyz {
xyz() : t(1) {}

const int t;
};

EDIT : Qoy, what compilers support that means of intialization? It doesn't seem like it could be supported, 'cause it is not static and you could have derived classes that want to initialize it to a different value.


[edited by - chiuyan on July 6, 2003 10:23:15 PM]

Share this post


Link to post
Share on other sites
Checked in TCPL (Stroustrup), 10.4.6.1-2: Constant members may (as I said) be initialised in the constructor''s initialiser list (in fact they must be, as there is no other way).

Members that are static const may be initialised inline (as Beerhunter said). Qoy''s statement is entirely incorrect, I''m afraid; only static members need to be defined separately of the class itself. However, there is an interesting problem where these two situations meet: Static const members that are required to be stored as objects in memory rather than be inlined (e.g. such members whose address is taken, that are pointed to, etc.) must be defined separately even if they are initialised inline - defined, but not reinitialised. (If, on the other hand, they don''t need an address, this is not necessary.)

Share this post


Link to post
Share on other sites