> The following compiles and runs. Notice: I used vector instead of list
just cause it was easier for me.
#include <iostream>
#include <string>
#include <vector>
class Pet
{
public:
virtual ~Pet() {};
private:
std::string name;
int feeding_times;
};
class Dog: public Pet
{
int play_time;
};
class Cat: public Pet
{
int kitty_litter_type;
};
class Fish: public Pet
{
int water_temp;
};
class Kennel
{
public:
std::vector<Pet*> bordered_pets;
void addPet(Pet* pet)
{
bordered_pets.push_back(pet);
}
void whatPet( int index )
{
if ( index >= bordered_pets.size() )
std::cout << "Bad Index" << std::endl;
else if ( typeid( *bordered_pets[index] ) == typeid( Dog ) )
std::cout << "it's a dog!" << std::endl;
else if ( typeid( *bordered_pets[index] ) == typeid( Cat ) )
std::cout << "It's a cat!" << std::endl;
else if ( typeid( *bordered_pets[index] ) == typeid( Fish ) )
std::cout << "It's a fish!" << std::endl;
else
std::cout << "I don't know what the heck this is!" << std::endl;
}
};
int main()
{
Dog* german_shepard = new Dog;
Cat* callico = new Cat;
Dog* dalmation = new Dog;
Fish* goldfish = new Fish;
Pet* catfish = new Fish;
Kennel kennel;
kennel.addPet(german_shepard);
kennel.addPet(callico);
kennel.addPet(dalmation);
kennel.addPet(goldfish);
kennel.addPet(catfish);
for ( int i = 0; i < 5; ++i )
kennel.whatPet( i );
std::string wait;
std::getline( std::cin, wait );
}
Ooops, I used new and I didn't use delete. This fixes that.
#include <iostream>
#include <string>
#include <vector>
class Pet
{
public:
virtual ~Pet() {};
private:
std::string name;
int feeding_times;
};
class Dog: public Pet
{
int play_time;
};
class Cat: public Pet
{
int kitty_litter_type;
};
class Fish: public Pet
{
int water_temp;
};
class Kennel
{
public:
std::vector<Pet*> bordered_pets;
void addPet(Pet* pet)
{
bordered_pets.push_back(pet);
}
void whatPet( int index )
{
if ( index >= bordered_pets.size() )
std::cout << "Bad Index" << std::endl;
else if ( typeid( *bordered_pets[index] ) == typeid( Dog ) )
std::cout << "it's a dog!" << std::endl;
else if ( typeid( *bordered_pets[index] ) == typeid( Cat ) )
std::cout << "It's a cat!" << std::endl;
else if ( typeid( *bordered_pets[index] ) == typeid( Fish ) )
std::cout << "It's a fish!" << std::endl;
else
std::cout << "I don't know what the heck this is!" << std::endl;
}
~Kennel()
{
for ( std::vector<Pet*>::iterator it = bordered_pets.begin(); it !=
bordered_pets.end(); ++it )
delete *it;
}
};
int main()
{
Dog* german_shepard = new Dog;
Cat* callico = new Cat;
Dog* dalmation = new Dog;
Fish* goldfish = new Fish;
Pet* catfish = new Fish;
Kennel kennel;
kennel.addPet(german_shepard);
kennel.addPet(callico);
kennel.addPet(dalmation);
kennel.addPet(goldfish);
kennel.addPet(catfish);
for ( int i = 0; i < 5; ++i )
kennel.whatPet( i );
std::string wait;
std::getline( std::cin, wait );
}