Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

I would expect them to be the same?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading