Tuesday, 13 August 2013

I want a vector of derived class pointers as base class pointers

I want a vector of derived class pointers as base class pointers

In C++, the vector class stores an array of objects. In this case, I am
storing pointers to derived class objects (Dogs). At some point, I want to
treat this vector as pointers to objects of the base class (Animals). This
is the "right"/non controversial way right? Why can't I do this?
#include <vector>
using namespace std;
class Animal { };
class Dog : public Animal { };
int main(int argc, char *argv[]) {
vector<Dog*> dogs;
dogs.push_back(new Dog());
dogs.push_back(new Dog());
vector<Animal*> animals = dogs; // This doesn't seem to work.
// This is really what I want to do...
vector<Animal*> all_animals[] = {dogs, cats, birds};
}
The error:
Untitled.cpp:11:18: error: no viable conversion from 'vector<class Dog *>'
to 'vector<class Animal *>'
vector<Animal*> animals = dogs;
^ ~~~~
/usr/include/c++/4.2.1/bits/stl_vector.h:231:7: note: candidate
constructor not viable: no known conversion from 'vector<Dog *>' to 'const
std::vector<Animal *, std::allocator<Animal *> > &' for 1st argument
vector(const vector& __x)
^

No comments:

Post a Comment