Default inheritance access specifier
If I have for example two classes A
and B
, such that class B
inherits A
as follows:
class B: public A
In this case, I'm doing public
inheritance.
If I write the previous code as follows:
class B: A
What type of inheritance will I be doing here (i.e; public)? In other words, what is the default access specifier?
Just a side question here. Do I call the previous line of codes statements
? Especially that I remember I read in the C++ Without Fear: A Beginner's Guide That Makes You Feel Smart book that statements
are that that end with ;
. What do you think about that?
Thanks.
Just a small addition to all the existing answers: the default type of the inheritance depends on the inheriting (derived) type (B
in the example), not on the one that is being inherited (base) (A
in the example).
For example:
class A {};
struct B: /* public */ A {};
struct A {};
class B: /* private */ A {};
It's private for class and public for struct.
Side answer: No, these are definitions of the class according to the standard. Class definition end with a semicolon. On the other hand not all statements end with a semicolon (e.g. an if
statement does not).
When you inherit a class from another class (inherit class Base
from class Derived
in this case), then the default access specifier is private
.
#include <stdio.h>
class Base {
public:
int x;
};
class Derived : Base { }; // is equilalent to class Derived : private Base {}
int main()
{
Derived d;
d.x = 20; // compiler error becuase inheritance is private
getchar();
return 0;
}
When you inherit a class from a structure (inherit class Base
from struct Derived
in this case), then the default access specifier is public
.
#include < stdio.h >
class Base {
public:
int x;
};
struct Derived: Base {}; // is equilalent to struct Derived : public Base {}
int main() {
Derived d;
d.x = 20; // works fine becuase inheritance is public
getchar();
return 0;
}