Home > Enterprise >  Inheritance: If private is default, why do these two examples not work the same way?
Inheritance: If private is default, why do these two examples not work the same way?

Time:01-31

I was working around with inheritance in C . To my knowledge if you don't specify, B will always inherit private from A.

So why does this code work:

struct A {};
struct B : A {};

int main(void)
{
    A b = B();
    return 0;
}

But this creates the "A is an inaccessible Base of B" error:

struct A {};
struct B : private A {};

int main(void)
{
    A b = B();
    return 0;
}

I would expect them to be the same?

CodePudding user response:

Private inheritance is the default if the derived class is defined using the word class.

If you create it using struct, then inheritance is public by default.

CodePudding user response:

From cppreference:

A class defined with the keyword struct has public access for its members and its base classes by default.

A class defined with the keyword class has private access for its members and its base classes by default.

Or from Derived Classes documentation

If access-specifier is omitted, it defaults to public for classes declared with class-key struct and to private for classes declared with class-key class.

The above quotes explain the behavior of your program.

  •  Tags:  
  • Related