C ++ cast vector <Inherited *> to vector <abstract *>

class Interface{}; class Foo: public Interface{}; class Bar{ public: vector<Interface*> getStuff(); private: vector<Foo*> stuff; }; 

How to implement getStuff() function?

+7
c ++ polymorphism casting vector
source share
3 answers
 vector<Interface*> result(stuff.begin(), stuff.end()); return result; 
+25
source share

std::vector<Inherited*> and std::vector<abstract*> are different and rather unrelated types. You cannot drop from one to another. But you can std::copy or use the iterator range constructor, as @Grozz says.

Edit:

Answering your question in the comments: they are different from each other, since two classes with members of compatible types are different. Example:

 struct Foo { char* ptr0; }; struct Bar { char* ptr1; }; Foo foo; Bar bar = foo; // boom - compile error 

For this last statement to work, you need to define an explicit assignment operator, for example:

 Bar& Bar::operator=( const Foo& foo ) { ptr1 = foo.ptr0; return *this; } 

Hope this makes it clear.

+5
source share

I am using this. This is not very nice, but quickly I think :)

 vector<Interface*> getStuff() { return *(std::vector<Interface*> *)&stuff; } 

And you can also only return a link to a vector using this method

 vector<Interface*> &getStuff() { return *(std::vector<Interface*> *)&stuff; } 
+1
source share

All Articles