Home > Mobile >  "Invalid base class" error when trying to inherit from derived struct (C )
"Invalid base class" error when trying to inherit from derived struct (C )

Time:01-22

I've got a "Base" struct, an "NPC" struct derived from the "Base". All works perfectly fine. But when I try to create a new struct called "PC" from the "NPC" struct, I get an error: "invalid base class". What's the problem? Is it not possible to create a struct from a derived struct?

struct Base
{
    char* name = 0;

    int MaxHP = 0;
    int CurrHP = 0;
};


struct NPC : Base
{
    int gold = 0;
    int stats[];
};

struct PC : NPC // I get the error here
{
    unsigned int ID = 0;
};

CodePudding user response:

When you wrote:

struct NPC : Base
{
    int gold = 0;
    int stats[]; //NOT VALID, this is a definition and size must be known
};

This is not valid as from cppreference:

Any of the following contexts requires type T to be complete:

  • declaration of a non-static class data member of type T;

But the type of the non-static data member stats is incomplete and hence the error.

CodePudding user response:

Yes, a struct can inherit from a class. The difference between the class and struct keywords is just a change in the default private/public specifiers. --> Here you need to specify the public keyword !

  struct Base
{
    char* name = 0;

    int MaxHP = 0;
    int CurrHP = 0;
};


struct NPC : public Base
{
    int gold = 0;
    int stats[];
};

struct PC :  public NPC 
    unsigned int ID = 0;
};

CodePudding user response:

dude you cannot perform inheritance on structures one of the major differences between structs and classes is inheritance. try this

class Base
{
    char* name = 0;

    int MaxHP = 0;
    int CurrHP = 0;
};


class NPC : Base
{
    int gold = 0;
    int stats[];
};

class PC : NPC // I get the error here
{
    unsigned int ID = 0;
};
  •  Tags:  
  • Related