#include <iostream>
#include <vector>
usingnamespace std;
class Animal
{
int type;
public:
Animal()
{
}
char *identify(){return"IM A ANIMAL";}
};
class Dog :public Animal
{
int nbarks;
public:
Dog()
{
}
char *idenify(){return"IM A DOG";}
};
class Cat:public Animal
{
int nmeows;
public:
Cat()
{
}
char *idenify(){return"IM A CAT";}
};
int main()
{
Cat cat;
Dog dog;
vector<Animal> animals;
animals.push_back(cat);
animals.push_back(dog);
cout<<animals.at(0).identify()<<endl;
cout<<animals.at(1).identify()<<endl;
cin.get()
return 1;
}
If anyone could help me with this tricky problem ill be grateful.
Basically i want to be able to place dervived objects Cat,Dog into a vector of Animal type and when i call the identify func get "IM A CAT" or "IM A DOG" etc.At the moment it just calls the base identify func which i dont want but at the same time i don't want a separate vector for cats and separate vector for dogs etc.
Look in to inheritance. If you were to change your base class into a pure virtual class, it would work fairly well for you. Basically, you just need to:
1) Get rid of the pointers to your members. They have their uses, but not in this case.
2) Change identify in class Animal to a virtual member.
3) Check your spelling. I saw that some of your functions aren't named properly.
#include <iostream>
#include <vector>
usingnamespace std;
class Animal
{
int type;
public:
Animal()
{
}
//virtual char *identify(){return "IM A ANIMAL";}
virtualchar *identify()=0;
};
class Dog :public Animal
{
int nbarks;
public:
Dog()
{
}
char *identify(){return"IM A DOG";}
};
class Cat:public Animal
{
int nmeows;
public:
Cat()
{
}
char *identify(){return"IM A CAT";}
};
int main()
{
Cat cat;
Dog dog;
vector<Animal> animals;
animals.push_back(cat);
animals.push_back(dog);
cout<<animals.at(0).identify()<<endl;
cout<<animals.at(1).identify()<<endl;
cin.get()
return 1;
}
I fixed the spelling and made the animal identify member func pure virtual however now im getting the following error C2259: 'Animal' : cannot instantiate abstract class.
When you set a method in a clas to = 0; you are signifying that is now an abstract base class. Setting a method to = 0; defines it as a pure virtual method. (note- it must be a method and it must be vitrual to be declared = 0;)
When a class contains any number of pure virtual methods it cannot be instantiated. But it can be inherited. The catch is that any class that inherits it MUST define any pure virtual functions. So by making a base class and abstract base class you are DEMANDING that all classes that inherit it have a minimum interface because that must redefine those pure virtual methods in order for them to be instantiated.