Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

gcc - Array of abstract classes (interfaces) in C++

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?

question from:https://stackoverflow.com/questions/65642546/array-of-abstract-classes-interfaces-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...