I have a rather strange situation where I would like to be able to define certain constants that a subclass of an ABC can override.
struct A {
static const int a = 20;
virtual int func() = 0;
};
struct B : public A {
static const int a = 3;
int func() { return 5; }
};
struct C : public A {
static const int a = 4;
int func() { return 3; }
};
Unfortunately, if I use A *aPtr = new B, aPtr->a will return 20, instead of 3.
One workaround I see is one-liner functions (along the lines of func in the above example), but the syntax of constants is quite a bit more appropriate for this particularly situation conceptually. Is there a syntactically reasonable way of resolving which constants to use at runtime, where the calling code doesn’t need to know anything after initial object creation?
Constants, especially static constants, cannot be overriden like you are asking for. You would have to use a virtual function instead:
Another option would be to use a template for the constant instead: