Home > Software engineering >  Why does compiler treat class as abstract?
Why does compiler treat class as abstract?

Time:10-20

I tried to compile the program, but compiler treats ParameterExpr class as abstract. I did not work with multiple inheritance and I thought that it should be work (because get_type was actually implemented in Expr class)

class IMetaExpression
{
public:
    virtual int get_type(void) = 0;
    virtual ~IMetaExpression(){}
};

class IParameterExpression : public IMetaExpression
{
public:
    virtual char get_parameter(void) = 0;
};
class Expr : public IMetaExpression
{
public:
    virtual int get_type(void) override { return 0; }
};
class ParameterExpr : public Expr, public IParameterExpression
{
public:
    virtual char get_parameter(void) override { return 'c';}
    //virtual int get_type(void) override { return 0; }
};
int main()
{
    auto p = new ParameterExpr();
    p->get_type();
    delete p;
    return 0;
}

CodePudding user response:

I believe this is an issue called the diamond problem. https://www.geeksforgeeks.org/multiple-inheritance-in-c/

This is where two classes inherit fully or partially from a base class, which then also has a child class inheriting both of these classes. Creating a diamond shape.

The solution to this is adding virtual to the inheritance of the two middle classes. Resulting in:

class IParameterExpression : virtual public IMetaExpression

and

class Expr : virtual public IMetaExpression

This allows the constructor of the base class to be called only once and sharing functionality between all inherited classes.

I am not an expert on the diamond problem, so more clarification is appreciated.

  • Related