Re: Best practice? Constant number in class
"Rune Allnor" <allnor@tele.ntnu.no> writes:
I have this class where I need a constant number. The number has no
interest outside the class, but is fairly important inside. The
naive way to do things is
class MyClass{
protected:
const double ImportantFactor = 3.14;
public:
};
but the compiler complains about initializing variables outside the
constructor. Of course, a const value can not be initialized after
declaration, which leaves me with a headache.
First of all, since ImportantFactor has the same value for all
instances, it ought not be a non-static data member. If you insist on
it being part of the class interface, make it a static data
member.
E.g.
class MyClass
{
protected:
static const double ImportantFactor;
};
Otherwise, move its declaration to the file where you implement the
member functions (i such a file exists).
Are there good ways of achieving this? I would, if possible, avoid
global variables or #define statements. One could, of course, define
a variable inside the class and set it to this value, but that seems
wrong, too...
Constant variables (including, normally, static data members of
classes) are initialized in their definition; but the above is not the
definition of ImportantFactor, but just a declaration.
The definition of ImportantFactor normally appears inside a
translation unit, and that's where the initialization belongs. E.g.:
double MyClass::ImportantFactor = 3.14;
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]