Default class inheritance access

C++Inheritance

C++ Problem Overview


Suppose I have a base and derived class:

class Base
{
    public:
    virtual void Do();
}

class Derived:Base
{
    public:
    virtual void Do();
}

int main()
{
    Derived sth;
    sth.Do(); // calls Derived::Do OK
    sth.Base::Do(); // ERROR; not calls Based::Do 
}

as seen I wish to access Base::Do through Derived. I get a compile error as "class Base in inaccessible" however when I declare Derive as

class Derived: public Base

it works ok.

I have read default inheritance access is public, then why I need to explicitly declare public inheritance here?

C++ Solutions


Solution 1 - C++

From standard docs, 11.2.2

>In the absence of an access-specifier for a base class, public is assumed when the derived class is defined with the class-key struct and private is assumed when the class is defined with the class-key class.

So, for structs the default is public and for classes, the default is private...

Examples from the standard docs itself,

class D3 : B { / ... / }; // B private by default

struct D6 : B { / ... / }; // B public by default

Solution 2 - C++

You might have read something incomplete or misleading. To quote Bjarne Stroustrup from "The C++ programming Language", fourth Ed., p. 602:

> In a class, members are by default private; in a struct, members > are by default public (§16.2.4).

This also holds for members inherited without access level specifier.

A widespread convention is, to use struct only for organization of pure data members. You correctly used a class to model and implement object behaviour.

Solution 3 - C++

The default inheritance level (in absence of an access-specifier for a base class )for class in C++ is private. [For struct it is public]

class Derived:Base

Base is privately inherited so you cannot do sth.Base::Do(); inside main() because Base::Do() is private inside Derived

Solution 4 - C++

The default type of the inheritance is private. In your code,

> class B:A

is nothing but

> class B: private A

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionpaul simmonsView Question on Stackoverflow
Solution 1 - C++liaKView Answer on Stackoverflow
Solution 2 - C++Peter G.View Answer on Stackoverflow
Solution 3 - C++Prasoon SauravView Answer on Stackoverflow
Solution 4 - C++SatishView Answer on Stackoverflow