static const in switch of derived class?
Hi
This simple code below compiles without error when pased into one file. But when I split the definitions and declarations into separate files (e.g. Base.h, Base.cpp, Derived.h, Derived.cpp - just as it should be), the compiler chokes at the switch statement complaining that msc_iCatIndex, msc_iDogIndex and msc_iBirdIndex are not constants. On the other hand, if I write something like msc_iCatIndex = 15; directly before the switch statement, the compiler complains that msc_iCatIndex is a const value.
Code:
class CBase
{
public:
static const int msc_iCatIndex;
static const int msc_iDogIndex;
static const int msc_iBirdIndex;
};
const int CBase::msc_iCatIndex = 1;
const int CBase::msc_iDogIndex = 2;
const int CBase::msc_iBirdIndex = 3;
class CDerived : public CBase
{
public:
char* GetAnimalName(int iAnimal); // may also be const
};
char* CDerived::GetAnimalName(int iAnimal)
{
// compiler chokes at this line with
// error 2166 "l-value specifies const object"
// CORRECT!
//msc_iCatIndex = 15;
// the three case statements choke with
// error 2051: "case expression not constant"
// COMPILER ERROR?
switch(iAnimal)
{
case msc_iCatIndex:
return "Cat";
case msc_iDogIndex:
return "Dog";
case msc_iBirdIndex:
return "Bird";
default:
break;
}
return "unknown";
}
Is this a compiler bug? How can I bypass this without putting all the code into one file?
Thank you in advance
Oliver.
Re: static const in switch of derived class?
Quote:
Originally posted by Oliver Twesten
.......
// error 2051: "case expression not constant"
// COMPILER ERROR?
switch(iAnimal)
{
case msc_iCatIndex:
....
For compiler it is error because you CAN modify constant value (any type) using typecasting.
Code:
const int msc_iCatIndex=40;
...
*((int*)&msc_iCatIndex) = 550; // This is valid and will change value!!!
For this reason compiler cannot generate code.
Another simple situation is: What if you get a 'const int' argument' value in a function and use it in switch statement?
Code:
void foo(const int n)
{
...
switch(...)
{
case n: // Will it be valid???
...
}