views:

112

answers:

2

Hi!

class Interface{};

class Foo: public Interface{};

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

how Do I implement the funtion getStuff() ?

hope the question is clear..

Thanks!

+19  A: 
vector<Interface*> result(stuff.begin(), stuff.end());
return result;
Grozz
+5  A: 

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

Edit:

Answering your question in the comments: they are different the same way 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 that last statement to work you'd need to define an explicit assignment operator like:

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

Hope this makes it clear.

Nikolai N Fetissov
can you explain me why they are different? in my point of view semantically every "vector of ptr_to_Inherited" IS also a "vector of ptr_to_abstract"
Mat