2

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.

wholock
  • 177
  • 1
  • 1
  • 8
  • If you want to check the type your design seems wrong and You should consider revisiting it.To know the type, You can use `typeinfo` of `dynamic_cast`. – Alok Save Oct 21 '12 at 13:22
  • 1
    list is wrong for this, because of slicing problem http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c – Industrial-antidepressant Oct 21 '12 at 13:24
  • 1
    You need to re-visit the design. What you probably need is virtual methods. An extension to this is the visitor pattern. – Martin York Oct 21 '12 at 16:35
  • possible duplicate of [C++ equivalent of instanceof](http://stackoverflow.com/questions/500493/c-equivalent-of-instanceof) – skolima Oct 21 '12 at 19:05

3 Answers3

2

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();
alestanis
  • 21,519
  • 4
  • 48
  • 67
2

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
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
0

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.

Slava
  • 1,528
  • 1
  • 15
  • 23