Search code examples
c++oopstlvectorpolymorphism

Conversion from STL vector of subclass to vector of base class


I am wondering if it is possible to convert a vector of derived class values to a vector of base class values. Specifically I want to be able to pass a vector of base class objects to a function whose formal parameters takes a vector of base class. It does not appear to be possible directly as the following code example produces an error (using g++):

#include <vector>

class A {
};

class B : public A {
};


void function(std::vector<A> objs) {
}

int main(int argc, char **argv) {
    std::vector<B> objs_b;
    objs_b.push_back(B());
    function(objs_b);
}

test.cc:16: error: conversion from ‘std::vector<B, std::allocator<B> >’ to non-scalar type ‘std::vector<A, std::allocator<A> >’ requested

I would like to be able to be able to call function without having to define a new vector with elements of type A, inserting my elements of type B or changing to a vector of pointers.


Solution

  • No, it is not. vector<B> is not derived from vector<A>, regardless of the fact that B is derived from A. You will have to change your function somehow.

    A more idiomatically C++ approach might be to template it and have it take a pair of iterators - this is why the various standard library functions (<algorithm> etc) work that way, because it separates the implementation of the algorithm from the kind of thing it's operating on.