In C++, is there any way to query the type of an object and then use that information to dynamically create a new object of the same type?
For example, say I have a
When there are extremely many classes deriving from the same base class then this code will save you from having to include clone methods every class. It's a more convenient way of cloning that involves templates and an intermediate subclass. It's doable if the hierarchy is shallow enough.
struct PureBase {
virtual Base* Clone() {
return nullptr;
};
};
template
struct Base : PureBase {
virtual Base* Clone() {
return new T();
}
};
struct Derived : Base {};
int main() {
PureBase* a = new Derived();
PureBase* b = a->Clone(); // typeid(*b) == typeid(Derived)
}