I have one class called Animal
class Animal
{
std::string name;
public:
Animal(string n)
{
name = n;
}
string getname()
{
return name;
}
};
and two inherited classes Cat and Dog
class Cat : public Animal
{
public:
Cat(string name):Animal(name)
{}
};
class Dog : public Animal
{
public:
Dog(string name):Animal(name){}
};
and i have a class called AnimalQueue which contains 2 lists, cat list and dog list
class AnimalQueue
{
std::list<Cat*> cats;
std::list<Dog*> dogs;
public:
void Enqueue(Animal a)
{
if(a.getname().compare("Cat") == 0)
{
// what should i do here
}
else
{
// what should i do here
}
}
};
what i want it, when i enter cat then it should go to the cat list and same with dog also in Enqueue function. I am not sure how it would work, how can i type cast from Animal to Cat or to Dog. I tried
Cat *c = (Cat*) &a;
but it dows not work.
int main()
{
string name = "Cat";
Cat c(name);
name = "Dog";
Dog d(name);
AnimalQueue aq;
aq.Enqueue(c);
aq.Enqueue(d);
}
This is working code, you can copy paste in your editor. you can change the signature of Animal or whatever you want so it can help to make my concept clear about type casting in inheritance.