"a struct has public inheritance by default" what does this statement really mean? And why is the following code in error just because I have omitted the keyword 'public' while deriving the 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 = ⅆ
cc->fun();
}
"a struct has public inheritance by default"
(B) Members of a class are private by default and members of struct are public by default. When deriving a struct from a class/struct, default access-specifier for a base class/struct is public and when deriving a class, default access specifier is private.
Structs cannot have inheritance, so have only one type. If you point two variables at the same struct, they have their own independent copy of the data. With objects, they both point at the same variable.
Classes and Structs (C++) The two constructs are identical in C++ except that in structs the default accessibility is public, whereas in classes the default is private.
It means that
struct c;
struct d : c
is equivalent to
struct d : public c
Your code is a class
extending a struct
:
struct c;
class d : c;
is equivalent to
class d : private c;
because class
has private inheritance by default.
And it means that all inherited and not overriden/overloaded/hidden methods from c
are private in d
.
"a struct has public inheritance by default" means that this
struct Derived : Base {};
is equivalent to
struct Derived : public Base {};
Classes have private inheritance by default, so when you remove the public
from a class inheritance you have the equivalent of
class Derived : private Base {};
In this private inheritance scenario, Derived
does not have an is-a relationship with Base
, it essentially has-a Base
. So the conversion you are trying to attempt here:
cc = ⅆ
is not allowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With