There are a few similar posts, here is my minimal case code:
bool useDerived=true;
BaseClass* maker;
if (useDerived) {
maker = new DerivedClass();
}
else {
maker = new BaseClass();
}
if (typeid(maker) == typeid(DerivedClass*)) {
cerr << "is derived type\n";
}
else {
cerr << "not derived type\n";
}
DerivedClass* x = dynamic_cast<DerivedClass*>(maker);
if (x == nullptr) {
cerr << " cannot cast back to derived\n";
}
else {
cerr << " cast to derived OK\n";
}
The result is:
not derived type
cast to derived OK
Am I missing something here? I include the <typeinfo>
header. Could it be a compiler version-specific bug?
The DerivedClass
is derived from the BaseClass
, and the DerivedClass
implements several virtual functions from the BaseClass
. The idea to use typeid is based on the blog section: Typeid as faster dynamic_cast.
typeid
is evaluated statically in this case. You should have dereferenced so you would give it a glvalue of polymorphic type, instead of some pointer type.
This line:
if (typeid(maker) == typeid(DerivedClass*)) {
should be:
if (typeid(*maker) == typeid(DerivedClass)) {