const member vars in a class?

Started by
6 comments, last by PHRICTION 20 years, 9 months ago
Dumb queston but.. Can I declare variable in a class to be constant? If so how do I initialize it?
Advertisement
You certainly can (though it''s not really a variable, then ...); IIRC, you can still initialise it in the constructor''s initialiser list.
hmm, wouldn''t you initialize a constant the normal way? in other words,

class xyz {
...
const int t = 1;
...
};
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
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]
This is also valid:

class Something {
public:
static const int Blah = 1;
};
Great. Thanks for the help guys.
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.)

This topic is closed to new replies.

Advertisement