All the time, I find myself doing something like this:
Animal *animal = ...
if (Cat *cat = dynamic_cast(animal)) {
...
}
else if (Dog *dog =
I think you actually want to use inheritance rather than typecasing (I've never seen it before, pretty neat :) ) or type-checking.
Small example:
class Animal {
public:
virtual void makeSound() = 0; // This is a pure virtual func - no implementation in base class
};
class Dog : public Animal {
public:
virtual void makeSound() { std::cout << "Woof!" << std::endl; }
}
class Cat : public Animal {
public:
virtual void makeSound() { std::cout << "Meow!" << std::endl; }
}
int main() {
Animal* obj = new Cat;
obj->makeSound(); // This will print "Meow!"
}
In this case, I wanted to print the animal-specific sound without specific type checking. To do so, I use the virtual function "makeSound" each subclass of Animal has and overrides to print the correct output for that animal.
Hope this is what you were aiming for.