this is my code
#include <iostream>
#include <vector>
#include <memory>
#include <tr1/memory>
using namespace std;
class Animal {
public:
string name;
Animal (const std::string& givenName) : name(givenName) {
}
};
class Dog: public Animal {
public:
Dog (const std::string& givenName) : Animal (givenName) {
}
string speak ()
{ return "Woof, woof!"; }
};
class Cat: public Animal {
public:
Cat (const std::string& givenName) : Animal (givenName) {
}
string speak ()
{ return "Meow..."; }
};
int main() {
vector<Animal> animals;
Dog * skip = new Dog("Skip");
animals.push_back( skip );
animals.push_back( new Cat("Snowball") );
for( int i = 0; i< animals.size(); ++i ) {
cout << animals[i]->name << " says: " << animals[i]->speak() << endl;
}
}
these are my errors:
index.cpp: In function ‘int main()’:
index.cpp:36: error: no matching function for call to ‘std::vector<Animal, std::allocator<Animal> >::push_back(Dog*&)’
/usr/include/c++/4.2.1/bits/stl_vector.h:600: note: candidates are: void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = Animal, _Alloc = std::allocator<Animal>]
index.cpp:37: error: no matching function for call to ‘std::vector<Animal, std::allocator<Animal> >::push_back(Cat*)’
/usr/include/c++/4.2.1/bits/stl_vector.h:600: note: candidates are: void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = Animal, _Alloc = std::allocator<Animal>]
index.cpp:40: error: base operand of ‘->’ has non-pointer type ‘Animal’
index.cpp:40: error: base operand of ‘->’ has non-pointer type ‘Animal’
What I want to do:
I just want to use a dynamic data structure that will go through a list of possible Animal objects.
I am trying to learn this polymorphism concept in C++ syntax.
I am familiar with Java and PHP but significantly less so with C++.
UPDATE:
I have added the changes as mentioned by one of the answers. http://pastebin.com/9anijwzQ
But I am getting errors regarding the unique_ptr. I have included memory. So I am not sure what the issue is.
http://pastebin.com/wP6vEVn6 is the error message.
There are two problems.
First, your vector contains
Animalobjects, and you are trying to fill it with pointers toAnimalderived types.AnimalandAnimal*are not the same type, so that operation wouldn’t usually compile.Second,
Animalhas no methodspeak(). If you were to push derived types ofAnimalinto the vector, you would get object slicing. You can avoid it by having your vector hold smart pointers toAnimal, for examplestd::vector<std::unique_ptr<Animal>>. But you still need to giveAnimalaspeak()virtual method. For example:Where I have made
Animal::speak()a pure virtual method and givenAnimala virtual destructor.See when to use virtual destructors and when should a virtual method be pure.