If I create a static const in the base class of my hierarchy, can I redefine its value in a derived class?
edit:
#include <iostream>
class Base
{
public:
static const int i = 1;
};
class Derived : public Base
{
public:
static const int i = 2;
};
int main()
{
std::cout << "Base::i == " << Base::i << std::endl;
std::cout << "Derived::i == " << Derived::i << std::endl;
Base * ptr;
ptr= new Derived;
std::cout<< "ptr=" << ptr->i << std::endl;
return 0;
}
…ptr refers to Base::i, which is undesirable.
Access via
ptrto static members is via its declared typeBase *and not its runtime type (sometimesBase *, sometimesDerived *). You can see this with the following trivial extension of your program:Output: