The fastest way to do this is to add a method to the superclass which returns something that represents the type of the child:
class MyBase {
public:
enum type { Base, DerivedA, DerivedB, DerivedC };
virtual type getType() const {
return Base;
}
virtual ~MyBase() {}
};
Then, you'll overload this method in each child class:
class MyDerivedA : public MyBase {
pubilc:
MyBase::type getType() const override {
return MyBase::type::DerivedA;
}
};
class MyDerivedB : public MyBase {
pubilc:
MyBase::type getType() const override {
return MyBase::type::DerivedB;
}
};
class MyDerivedC : public MyBase {
pubilc:
MyBase::type getType() const override {
return MyBase::type::DerivedC;
}
};
This method is a little tedious, but it'll work fine. That being said, this brings us to the big issue.
Why is using dynamic_cast discouraged?
From a technical standpoint, there is nothing wrong with dynamic_cast. Use it when you need it. In this particular case, there's a good chance you need it.
However, having to figure out the specific derived type of a class oftentimes indicates a design flaw. Having inheritance and virtual methods is supposed to eliminate the need to know the derived type.
That's why dynamic_cast is discouraged.