Pergunta

I hope you can help me with the following problem. I am trying to create a flexible system of interfaces and hit a problem. This is the relevant code:

// Interface 1
//      this: virtual f_a
// -> abstract
struct I_A abstract
{
    virtual void f_a() = 0;
};

// Interface 2
//      I_A : virtual f_a
//      this: virtual f_b
// -> abstract
struct I_B abstract : public I_A
{
    virtual void f_b() = 0;
};

// Implementation 1
//      I_A : virtual f_a
//      zhis: defines f_a
// -> not abstract
struct S_A : public I_A
{
    virtual void f_a() {}
};

// Implementation 2
//      I_B : virtual f_a
//      I_B : virtual f_b
//      S_A : defines f_a
//      this: defines f_b
// -> not abstract
struct S_B : public I_B, public S_A
{
    virtual void f_b() {}
};

I cannot instantiate S_B because the compiler states it is abstract. What is wrong?

Foi útil?

Solução

You need to use virtual inheritance here:

struct I_A
{
    virtual void f_a() = 0;
};

struct I_B : virtual public I_A
{
    virtual void f_b() = 0;
};


struct S_A : virtual public I_A
{
    virtual void f_a() {}
};

Note 1: I am ignoring your abstract statements in the class declarations, since it isn't standard C++.

Note 2: There is a duplicate of this here, where you can find explanations as to why this happens.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top