Re: Static Class Variables, Inheritance, and Polymorphism
crjjrc wrote:
Hi, I've got a base class and some derived classes that look something
like this:
class Base {
public:
int getType() { return type; }
private:
static const int type = 0;
};
class Derived1 : public Base {
private:
static const int type = 1;
};
class Derived2 : public Base {
private:
static const int type = 2;
};
I've then got a vector declared to hold instances of Base, but it's
actually filled with various instances of Derived1 and Derived2. On
iterating through and examining each item, I'd like to be able to call
getType() and have the correct derived class's class variable
retrieved. However, I only get 0 returned. I've tried making
getType() virtual in the Base class, but that didn't help anything.
I can get this to work by defining getType() in each class to return a
literal 0, 1, or 2, but I'd think that what I'm trying do should
work. Any ideas? I don't want to dynamically cast if I can avoid it.
Thanks for any help! Let me know if I can frame the problem
differently or provide more info.
- Chris
class Base {
public:
virtual int getType() { return type; }
private:
static const int type = 0;
};
class Derived1 : public Base {
private:
static const int type = 1;
public:
int getType() { return type; }
};
class Derived2 : public Base {
private:
static const int type = 2;
public:
int getType() { return type; }
};
int main(void) {
std::vector<Base*> v;
v.push_back(new Derived1);
v.push_back(new Derived2);
v.push_back(new Derived2);
v.push_back(new Derived1);
v.push_back(new Base);
for (std::vector<Base*>::iterator i = v.begin(); i != v.end(); ++i){
std::cout << (*i)->getType() << std::endl;
}
return 0;
}
I guess I'm assuming you actually want Base to be a non-abstract
class... you may want to have base look more like
class Base {
public:
virtual int getType()=0;
};
and remember now you are not allowed to instantiate Base directly...