Access to default class inheritance

Suppose I have a base and a 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 } 

apparently, I want to access the :: Do through Derived database. I get a compilation error as a โ€œBase class inaccessibleโ€, however, when I declare Derive as

 class Derived: public Base 

It works fine.

I read the default access for public inheritance, then why do I need to explicitly declare public inheritance here?

+41
c ++ inheritance
Sep 28 '10 at 9:33
source share
4 answers

You may have read something incomplete or misleading. To quote Bjarne Stroustrup from โ€œC ++ Programming Language,โ€ fourth editor, p. 602:

In the class the default members are private ; in a struct , the default members are public (ยง16.2.4).

This also applies to members inherited without an access level qualifier.

A widespread convention is to use the structure only to organize pure data members. You used the class correctly to model and implement the behavior of an object.

+30
Sep 28 '10 at 9:35 on
source share

From standard documents, 11.2.2

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

So, for struct , the default is public , and for class es, the default is private ...

Examples from the standard documents themselves,

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

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

+97
Sep 28 '10 at 9:41
source share

The default inheritance level (in the absence of an access specifier for the base class) for a class in C ++ is private. [For struct this is publicly available]

class Derived:Base

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

+9
Sep 28 '10 at 9:40
source share

The default inheritance type is private. In your code

class B: A

- it is nothing but

Class B: Private A

+4
Mar 04 '15 at 9:06
source share



All Articles