Consider this simple example:
#include <iostream>
#include <vector>
class Interface {
public:
virtual int nullary() = 0;
virtual ~Interface() = default;
};
class SubClass1 : public Interface {
public:
int nullary() override { return 1; }
};
class SubClass2 : public Interface {
public:
int nullary() override { return 2; }
};
class AnotherClass {
private:
std::vector<Interface> elems_;
public:
explicit AnotherClass(const std::vector<Interface>& elems) : elems_{elems} {}
};
int main() {
return 0;
}
Ideally, Anotherclass
can be instantiated with a vector of SubClass1
or SubClass2
.
However, when I try to compile this, I get the following error:
error: allocating an object of abstract class type 'Interface'
Is a use of template the correct option? What's the right way to compile this code?