user5540335
user5540335

Reputation:

Derived class remains abstract

Why is the class TB abstract in the following code?

#include <stdio.h>

struct IA
{
    virtual long X() = 0;
};
struct IB: public IA
{
    virtual long Y() = 0;
};

struct TA: public IA
{
    virtual long X() { return 5; };
};

struct TB: public IB, public TA
{
   // virtual long X() { return TA:: X(); };
    virtual long Y() { return 7; };
};

int main()
{
    TB b;
}


main.cpp:25: error: cannot declare variable 'b' to be of abstract type 'TB'
     TB b;

Upvotes: 0

Views: 69

Answers (1)

amc176
amc176

Reputation: 1544

The problem is that TB is inheriting twice from IA because IA is parent of both IB and TA. To fix it you need to either redesign your class hierarchy or use virtual inheritance:

#include <stdio.h>

struct IA
{
    virtual long X() = 0;
};
struct IB: public virtual IA // virtual inheritance here
{
    virtual long Y() = 0;
};

struct TA: public virtual IA // and here
{
    virtual long X() { return 5; };
};

struct TB: public IB, public TA
{
   // virtual long X() { return TA:: X(); };
    virtual long Y() { return 7; };
};

int main()
{
    TB b;
}

Upvotes: 6

Related Questions