1

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?

gust
  • 878
  • 9
  • 23
  • 1
    `std::vector` -> `std::vector>`. Polymorphism requires a pointer/reference to work – NathanOliver Jul 28 '22 at 21:35
  • So do you want to only store objects of either `SubClass1` *or* `SubClass2` in `AnotherClass` or a mix of both? – UnholySheep Jul 28 '22 at 21:35
  • @UnholySheep should be just one. Either `SubClass1` or `SubClass2`. But it shouldn't just be a static variant since more extensions could be added (ideally, it would be a dynamic dispatch). – gust Jul 28 '22 at 21:36
  • 1
    In that class it might be possible to turn `AnotherClass` into a template (combined with a `std::is_base_of` check) - though that also depends on how `AnotherClass` is intended to be used – UnholySheep Jul 28 '22 at 21:38
  • You cannot instantiate an object of the abstract type `Interface`, so you must use pointers instead, like `std::vector`. As @NathanOliver points out, `unique_ptr` is even better. – jkb Jul 28 '22 at 21:38
  • A concrete solution depends strongly on how exactly you intent to use the class. From what you have said so far it seems that all you really need to do is add `template` before `class AnotherClass` (and maybe some base class check as mentioned above and maybe some abstract base class for the template specializations as well). – user17732522 Jul 28 '22 at 21:49

0 Answers0