Using RTTI (Run-Time Type Information) versus implementing a custom type identification system involves several trade-offs:
RTTI can have a slight performance overhead due to the additional type information stored in the compiled binary. A custom system might be optimized for your specific needs, potentially offering better performance.
#include <iostream>
#include <typeinfo>
class Monster {
public:
virtual ~Monster() {}
};
class Dragon : public Monster {};
void useRTTI(Monster* m) {
if (typeid(*m) == typeid(Dragon)) {
std::cout << "It's a Dragon!\n";
}
}
// Custom type identification
enum class MonsterType { Base, Dragon };
class CustomMonster {
public:
virtual MonsterType getType() const {
return MonsterType::Base;
}
};
class CustomDragon : public CustomMonster {
public:
MonsterType getType() const override {
return MonsterType::Dragon;
}
};
void useCustom(CustomMonster* m) {
if (m->getType() == MonsterType::Dragon) {
std::cout << "It's a CustomDragon!\n";
}
}
int main() {
// Using RTTI
Monster* m1 = new Monster();
Monster* d1 = new Dragon();
std::cout << "Using RTTI:\n";
useRTTI(m1); // Should not print anything
useRTTI(d1); // Should print "It's a Dragon!"
// Using Custom Type Identification
CustomMonster* m2 = new CustomMonster();
CustomMonster* d2 = new CustomDragon();
std::cout << "Using Custom Type Identification:\n";
// Should not print anything
useCustom(m2);
// Should print "It's a CustomDragon!"
useCustom(d2);
// Clean up
delete m1;
delete d1;
delete m2;
delete d2;
}
Using RTTI:
It's a Dragon!
Using Custom Type Identification:
It's a CustomDragon!
RTTI is standardized and works with any type, including those from third-party libraries. A custom system might be more tailored to your specific needs but could be less flexible with external types.
RTTI is built into the language, so it's consistent across different codebases. A custom system requires maintenance and documentation, which can be an overhead as your project grows.
RTTI can be disabled at compile-time for optimization, while a custom system is always available. This can be an advantage or disadvantage depending on your needs.
RTTI has a standardized API that most C++ developers are familiar with. A custom system requires learning and understanding specific to your implementation.
In general, if performance is critical and you have a well-defined set of types, a custom system might be preferable. For general-purpose applications where flexibility and standardization are more important, RTTI is often the better choice.
Answers to questions are automatically generated and may not have been reviewed.
typeid()
Learn to identify and react to object types at runtime using RTTI, dynamic casting and the typeid()
operator