Reputation: 187
For example we have an Animal class ,and we created some other class such as Lion class,Tiger class,etc. I have made a list of the Animal class and I want to transverse the list and process the list according to the type of the class of the every member in the list.
Class Animal
Class Tiger :: public Animal{}
Class Lion :: public Animal{}
list<Animal> l;
Tiger T;
Lion L;
l.push_back(T); l.push_back(L);
if the top member of the list is Tiger print"ITs a tiger"
else print"something"
Simply, I want to check the type of the instance created. I don't know how to do it.
Upvotes: 2
Views: 168
Reputation: 1524
use dynamic_cast and check whether result is valid. But!!!!!!! You it is usually a bad practice: in your case it is better in the base class to declare virtual function virtual std::string printMe() const = 0; and implement it in each class.
Upvotes: 0
Reputation: 21863
This is called RTTI and it's not good coding practice.
This being said, if you absolutely want to know a class' type, you can do
if (typeid(myanimal) == typeid(Tiger)) {
// Do something tiger-like
}
What I would recommend in your case is to have a common interface to all Animal
, for instance a sayHello()
method. You would have
class Animal {
void sayHello() = 0;
// Other things
}
In Tiger
this would be
Tiger::sayHello() {
cout << "Hello I'm a Tiger!" << endl;
}
Then, from your vector<Animal*>
(you need to use pointers) just call
myAnimal->sayHello();
Upvotes: 2
Reputation: 258608
You can check for the type (typeid
), yes, but you don't need to.
You can just hold a std::list<std::unique_ptr<Animal> >
and have a virtual
method in Animal
. This way you're taking advantage of polymorphism.
class Animal
{
public:
virtual void print() = 0;
};
class Tiger : Animal
{
virtual void print() { std::cout << "I'm a tiger"; }
};
Animal* pA = new Tiger;
pA->print(); // prints tiger
Upvotes: 2