I made a class called A
that has a virtual method do_something
:
class A {
virtual int do_something() = 0;
}
B
subclasses A
:
class B {
virtual int do_something() {
return 42;
}
}
Somewhere in my main function, I do this.
vector<A> arr;
arr.push_back(B());
int val = arr[0].do_something();
However, I get a compiler error complaining that do_something
is a pure virtual function. I believe this is because I declared the vector to contain objects of type A
, and A
is an abstract class. The compiler thus doesn't know to look in class B
to see if do_something
is define.
Is there a way around this? Can I still store a vector of objects of different types (with a common superclass though that declares a common virtual function)?