Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default class inheritance access

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?

like image 293
paul simmons Avatar asked Sep 28 '10 09:09

paul simmons


People also ask

What is the default access type for inheritance?

If you do not choose an inheritance type, C++ defaults to private inheritance (just like members default to private access if you do not specify otherwise). That gives us 9 combinations: 3 member access specifiers (public, private, and protected), and 3 inheritance types (public, private, and protected).

Are default fields inherited in Java?

Every field is inherited, even private fields. The fact that the subclass can't access it does not mean that it is not there.

Are default variables inherited?

All subclasses will inherit all default variables in the same package only. Subclasses outside the package will not inherit any default members.

Which is default inheritance of class Swift?

Inheritance allows us to create a new class from an existing class. The new class that is created is known as subclass (child or derived class) and the existing class from which the child class is derived is known as superclass (parent or base class). Here, we are inheriting the Dog subclass from the Animal superclass.


1 Answers

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

like image 84
liaK Avatar answered Oct 11 '22 23:10

liaK