Typical example:
class Value
{
public:
virtual ~Value();
};
class RationalNumber : public Value
{
...
}
Value *v = new RationalNumber(...)
...
RationalNumber* test = dynamic_cast<RationalNumber*>(v);
if (v)
cout << "v is a rational number" << endl;
else
cout << "v is a not rational number" << endl;
Note however that this is NOT a good solution in nearly all cases where you have inheritance. I'm writing a compiler, and it's the first time I've ever used dynamic_cast
- mostly because there are some fairly generic functions that deal with (for example) ExprAST
class pointers, and to add ALL of the variants of functions that all the derived classes (31 classes at present count) of has into the ExprAST
would be rather unpractical. (And of course, having a call that does expr->isVariableExprAST()
is not that much better than VariableExprAST* var = dynamic_cast<VariableExprAST*>(expr); if (var) ...
- it's the same amount of code, more or less).
But in most cases, NOT knowing what type you deal with is a much better solution.
A more suitable solution is to use a virtual function that is common for all classes, e.g:
class Value
{
public:
virtual ~Value();
virtual void SomeMethod() = 0;
};
class RationalNumber : public Value
{
...
virtual void SomeMethod() { ... }
}
class IrrationalNumber : public Value
{
...
virtual void SomeMethod() { ... }
}
Value *v = ...
v->SomeMethod();
In this case, you will not need to do ANY checks - you just need to implement the method SomeMethod
for all subtypes.