• ### Announcements

#### Archived

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

# C++ Class constant question

## Recommended Posts

I want to do something like the following:

class MyObject
{
static int OBJECT_ID = 1000;
};

Manager::Observer(MyObject::OBJECT_ID);

switch (objectId)
{
case MyObject::OBJECT_ID
{
break;
}
};  
This is a contrite example but hopefully you get the picture. I''ve seen this used and explained on a number of websites, but it won''t compile under VC6 for me.
quote:
error C2258: illegal pure syntax, must be ''= 0''
Also, it won''t let me use the constant in the case statement as apparently it''s not a constant value. Is what I want possible? If it is, how so? Where am I going wrong? Thanks

##### Share on other sites
You can use an enum instead of a static int.

Thanks...

##### Share on other sites
First off, you can''t initialize variables within the class''s declaration. And for static variables, you have to initialize them in the .cpp file for the class, or else the compiler will not allow you to use them. So you would need to do something like this:

MyObject.h:
class MyObject{    static int OBJECT_ID;};

MyObject.cpp:
int MyObject::OBJECT_ID = 1000;

I''m kind of lost as to exactly what you are trying to do here:
Manager::Observer(MyObject::OBJECT_ID);switch (objectId){      case MyObject::OBJECT_ID   {      break;   }};

##### Share on other sites
You can't do switch/case with non-const values. Either use enum like pawn69 said or use "static const int OBJECT_ID = 1000;". Or if it needs to be non-const, declare and define it as Lunatic Raven said and then use normal 'if' instead

if (objectId == MyObject::OBJECT_ID) {}

[edited by - civguy on January 30, 2003 4:14:00 PM]

• ### Forum Statistics

• Total Topics
627707
• Total Posts
2978721

• 21
• 14
• 12
• 22
• 35