There is a mammal class and dog + cat inherit mammal.
If I had a function to which you pass a mammal pointer but it is intended to be passed a dog or cat, how could you check what type of class was passed?
Printable View
There is a mammal class and dog + cat inherit mammal.
If I had a function to which you pass a mammal pointer but it is intended to be passed a dog or cat, how could you check what type of class was passed?
I donīt know if typeid works with polimorphism, but you could store a string in the class that says what it is
I'm not sure why you would need to know. If you are passing a base class pointer to some function you should probably be changing / setting things that are common members in the base class. I guess you could use typeid if you really wanted to but, imo, for the case you are describing it would be poor design.
I agree with MrWizard, but if you really need to, here are a couple ideas:
The other possibility is to dynamic_cast:Code:// Not a particularly good idea...
class base
{
std::string type_;
public:
base(std::string str) : type_(str) {}
virtual std::string type() const;
};
class a : public base
{
public:
a() : base("a") {}
...
};
// later on...
voif foo(base* x)
{
if(x->type() == "a") ...
}
Again, you really shouldn't need to no in most cases, and there usually is a better was around.Code:// A slightly better idea
template<typename T, typename U>
bool is_type(U* x)
{
return (dynamic_cast<T*>(x) != 0);
}
// later on...
void foo(mammal* x)
{
if(is_type<cat>(x)) ...
}