musicmatze
musicmatze

Reputation: 4288

Pass a vector of baseclass to a function which takes vector of superclass

In my code, I have a SuperType which has two SubTypes ... now I have a std::vector<SubTypeA>& and need to pass this to a function which iterates over the vector and calls only functions from the SuperType ... I need to do this with both subtypes.

(The supertype is not virtual yet, but I need to make it virtual at some point, because it is just the common part of the two subtypes and there can't be an instance of it)

Here is a minimal (non)working example:

#include <vector>
struct Super {
    // stuff and functions
};
struct SubTypeA : public Super {
    // stuff and functions
};

void func(const std::vector<Super>& sup) {
    for (auto& elem: sup) {
        // do things
    }
    return;
}

int main() {
    std::vector<SubTypeA> v; // I get this from another place
    std::vector<SubTypeA>& my_variable = v; // this is what I have in my code
    func(my_variable); // does not work.
}

passing an iterator would be a solution, too.


Sidenote: I get the my_variable from another type:

struct SomeContainer {
    std::vector<SubTypeA> a;
    std::vector<SubTypeB> b;
}

And I wouldn't like to change the container, so std::vector<SubTypeA>& it is.

Upvotes: 0

Views: 375

Answers (1)

user2807083
user2807083

Reputation: 2972

In c++ references and pointers of types Super and SubTypeA are covariant, but std::vector<Super> and std::vector<SubTypeA> are not. You can use vector of pointers or references to base class to achieve what you want:

#include <vector>
struct Super {
    // stuff and functions
};
struct SubTypeA : public Super {
    // stuff and functions
};

void func(std::vector<std::reference_wrapper<Super>>& sup) {
    for (Super& elem: sup) {
        // do things
    }
    return;
}

int main() {
    std::vector<SubTypeA> v; // I get this from another place
    // using vector of references to base class
    std::vector<std::reference_wrapper<Super>> my_variable(v.begin(), v.end());        

    func(my_variable); // does not work.
}

Updated as recommended in comments

Upvotes: 3

Related Questions