This is my code:
class Base { /* something */ };
class Derived : public Base { /* something */ };
vector<Base*> v; // somebody else initializes it, somewhere
int counter = 0;
for (vector<Base*>::iterator i=v.begin(); i!=v.end(); ++i) {
if (typeof(*i) == "Derived") { // this line is NOT correct
counter++;
}
}
cout << "Found " << counter << " derived classes";
One line in the code is NOT correct. How should I write it properly? Many thanks in advance!
The names of
typeidare implementation-defined and you shouldn’t make assumptions about them. However, you could compare two typeid’s.Generally it would be considered a bad design (but if the purpose is just to write a not very practical program to count instances of Derived, it’s just fine).
Note that this also requires Base to have a vtable (virtual functions and/or destructor), because non-polymorphic types just don’t have a dynamic type which
typeidchecks (that is, they would all be instances ofBaseas far astypeidis concerned).If you don’t have any virtual functions, then you’ll need to emulate this yourself. For example, if you like string comparisons and don’t mind the overhead, add a field to
Basethat each type will fill out in its constructor and compare those. Otherwise use a unique integral identifier for each subtype etc.