"structure has default inheritance by default"

"structure has default inheritance by default" what does this statement mean? And why is the following code an error just because I omitted the keyword "public" when listing class d from c ??

struct c { protected: int i; public: c(int ii=0):i(ii){} virtual c *fun(); }; c* c::fun(){ cout<<"in c"; return &c(); } class d : c { public: d(){} d* fun() { i = 9; cout<<"in d"<<'\t'<<i; return &d(); } }; int main() { c *cc; d dd; cc = &dd; cc->fun(); } 
+6
source share
3 answers

It means that

 struct c; struct d : c 

equivalently

 struct d : public c 

Your class code extending struct :

 struct c; class d : c; 

equivalently

 class d : private c; 

because class has its own inheritance by default.

And that means that all inherited, not overridden / overloaded / hidden methods from c are private in d .

+9
source

"structure has default inheritance by default" means that this

 struct Derived : Base {}; 

equivalently

 struct Derived : public Base {}; 

Classes have private default inheritance, so when you remove public from class inheritance, you have the equivalent

 class Derived : private Base {}; 

In this private inheritance scenario, Derived has no is-a relationship with Base , it essentially has-a Base . So, the conversion you are trying to do here:

 cc = &dd; 

is not allowed.

+5
source

When you write a struct and inherit something without specifying an access specifier, this inheritance is treated as public . When you write a class and inherit something without specifying an access specifier (even if it is something struct ), this inheritance is treated as personal. In your code, you do the latter, so inheritance is private, hence the observed error.

In other words, saying that struct inheritance is public by default, it actually means that inheritance when writing to struct is public by default, and not that inheritance from struct is public by default.

+2
source

Source: https://habr.com/ru/post/915035/


All Articles