If I were to do this
class Gone
{
public:
static const int a = 3;
}
it works but if do
class Gone
{
public:
static int a = 3;
}
it gives a compile error. Now I know why the second one doesn’t work, I just don’t know why the first one does.
Thanks in advance.
This trick works only for constant compile-time expressions. Consider the following simple example:
It works just fine, because compiler knows that
Foo::baris 0 and never changes. Thus, it optimizes the whole thing away.However, the whole thing breaks once you take the address of that variable like this:
Linker sends you to fix the program because compile-time constants don’t have addresses.
Now, the second case in your example doesn’t work simply because a non-constant variable cannot be a constant compile-time expression. Thus, you have to define it somewhere and cannot assign any values in initialization.
C++11, by the way, has
constexpr. You can check Generalized constant expressions wiki (or C++11 standard :-)) for more info.Also, be careful – with some toolchains you will never be able to link program as listed in your first example when optimizations are turned off, even if you never take an address of those variables. I think there is a
BOOST_STATIC_CONSTANTmacro in Boost to work around this problem (not sure if it works though because I reckon seeing linkage failures with some old gcc even with that macro).