Archived

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

FunkyTune

Static const member variables in a class?

Recommended Posts

How do I declare a static const member variable in a class? I figured it should be something like this, but VC++ 6 won't let me. I found out a way to do it in Borland 5.02, but that didn't work in VC++ either. When I STFW:d i found a site saying that the syntax for doing this changed late in the C++ specification. Does anyone know of a way that works both in Borland 5.02 and VC++ 6?
    
class Foo
{
public:
   static const int MAXLENGTH=50;
};

void main()
{
   int max = Foo::MAXLENGTH;
}
    
/John [edited by - FunkyTune on October 16, 2002 10:01:57 AM]

Share this post


Link to post
Share on other sites
you have to declare it at filescope, so just put this under the class definition:
const int Foo::MAXLENGTH = 50;
so your whole code should look like this:


  

class Foo
{
public:
static const int MAXLENGTH;
};

const int Foo::MAXLENGTH = 50;

void main()
{
int max = Foo::MAXLENGTH;
}





Runicsoft -- home of my open source Function Parser and more

[edited by - Burning_Ice on October 16, 2002 10:18:52 AM]

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
FWIW, what you have originally is *valid* C++ code. VC6 is just too anal to compile it. VC7 compiles it beautifully though (and Borland, and GCC, and god knows how many other good compilers).

For now, if you don''t want to *define* it at filescope, you can use the "enum hack":


  
class Foo
{
public:
enum { MAXLENGTH = 50 };
}
void main()
{
int max = Foo::MAXLENGTH;
}

Share this post


Link to post
Share on other sites