-1

I want to store few animals in a vector. Animals may be Cats or Dogs. Later I want cats and dogs back from the vector. Can I use type casting here?

eg.

class Animal{

string name;

void makeSound();

}

class Dog:public Animal{

string owner;

void makeSound(){

cout << "Woof";

}

class Cat:public Animal{

string home;

void makeSound(){

cout << "Mew";

}

in main program.

vector<Animal> list;

Cat c = Cat();

list.push_back(c);

Cat cat = (Cat)list.at(0);   // how can I do this

PS:

This is not the exact code with syntax. But I need to do something like this.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
user3946110
  • 122
  • 1
  • 9

1 Answers1

2

You can store pointer to Animal in your vector like:-

std::vector<Animal*> vec;

There should be no need to explicitly check which type of object you are storing in vector...After all that's the essence of virtual functions in C++.

Anyway if you want it then :-

void func( Animal* ptr )
{
   if ( Cat* cat = dynamic_cast<Cat*>(ptr) )
      //cat type
   if ( Dog* dog = dynamic_cast<Dog*> (ptr) )
      //dog type
}
ravi
  • 10,994
  • 1
  • 18
  • 36
  • I googled and consulted few friends. This is the answer I needed. Always use pointers when you need to do things like this was an advice. :) – user3946110 Nov 18 '14 at 11:12