0

I want to declare an array of interfaces and further get a pointer to the list of interfaces Interface*. But compiler (GCC) prints error error: invalid abstract 'type Interface' for 'array'. Code:

class Interface {
public:
    virtual ~Interface() = default;

    virtual void Method() = 0;
};

class Implementation : public Interface {
public:
    void Method() override {
        // ...
    }
};

class ImplementationNumberTwo : public Interface {
public:
    void Method() override {
        // ...
    }
};

// there is an error
static const Interface array[] = {
        Implementation(),
        ImplementationNumberTwo(),
        Implementation()
};

How can I solve it?

  • Defining an array of `Interface` requires that `Interface` can be instantiated. It cannot. You need an array of pointers (e.g. `Interface *`) or smart pointers (e.g. `std::unique_ptr`). I'll leave initialisation as an exercise - but it will differ from what you are trying. – Peter Jan 09 '21 at 12:26

1 Answers1

2

You cannot create an Interface object since it's an abstract type. Even if Interface were not abstract what you are trying would not work because of object slicing. Instead you need to create an array of Interface pointers, e.g.

static Interface* const array[] = {
    new Implementation(),
    new ImplementationNumberTwo(),
    new Implementation()
};

In C++ polymorphism only works through pointers (or references).

Of course using dynamic allocation to create the Interface objects brings in new issues, like how those objects get deleted, but that's a separate issue.

john
  • 85,011
  • 4
  • 57
  • 81