Is it possible to declare a virtual static constant value in a C++ class?
A static
method cannot be virtual
, and no data members can be virtual
.
But you can hide static
fields in derived classes and use a virtual
method to return them.
class A
{
public:
static const int ID = 0;
virtual int getID() { return A::ID; }
};
class B : A
{
public:
static const int ID = 1;
virtual int getID() { return B::ID; }
};
Alternative:
class A
{
public:
A(int id = 0) : ID(id) {}
const int ID;
getID() { return ID; }
};
class B : public A
{
public:
B() : A(1) {}
};