tags:

views:

118

answers:

3

In C++, say I have a class Thing, I'd like it to include a const member of that type, something like:

class Thing
{
    public:
        Thing();
    private:
        static const Thing THING;
};

But I don't think this works as above. How can I do this?

A: 

I'm not sure what the standard says about this, but I don't see why it shouldn't work. It compiles fine on my gcc. Did you remember to instantiate the static object outside of the class declaration?

int3
No, I didn't do that. I guess I thought the declaration would mean it would instantiate itself with the default constructor. Thanks.
Tarquila
+3  A: 

The following little program compiles and links using GCC 3.4.5 (MinGW):

class Thing
{
public:
    Thing();
private:
    static const Thing THING;
};

Thing::Thing()
{}

// We must instantiate the static variable somewhere, like inside 'Thing.cpp'
const Thing Thing::THING = Thing();

int main(int argc, char* argv[])
{   
  return 0;
}
S.C. Madsen
A: 

No. You can't.
As S.C.Madsen and int3 already posted, you can declare static const in class scope for any type, as long as it is properly defined (in the cpp file) and initialized, But it can't be a compile time constant.
Compile time constant is a constant you can use as template argument and as built in arrays' size. These constants may also be optimized better than run-time constants. Currently, AFAIK, only the built in numeric types may serve as compile time constants.
The reason, BTW, is that this constant should be evaluated at compile time (similarly to literals).

Oren S