I have a class A
and its subclass B
and a method that takes std::vector<A>
. And I cannot make it work by passing std::vector<B>
.
I though that if subclass B
can be casted to A
, I should be able to pass vector of B
s to method that takes vector of A
s. How can I do that properly?
#include <iostream>
#include <vector>
class A {
public:
A() {}
};
class B: public A {
public:
B(): A() {}
};
void method(std::vector<A> a) {}
int main() {
std::vector<B> b;
method(b);
return 0;
}
When compiled:
g++ ex-cast-tag.cpp -std=c++11
ex-cast-tag.cpp:22:5: error: no matching function for call to 'method'
method(b);
^~~~~~
ex-cast-tag.cpp:18:6: note: candidate function not viable: no known conversion from 'vector<B>' to 'vector<A>'
for 1st argument
void method(std::vector<A> a) {}
^
1 error generated.
Thanks in advance!