Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"a struct has public inheritance by default"

"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 = &dd;
    cc->fun();
}
like image 893
user1232138 Avatar asked May 06 '12 18:05

user1232138


People also ask

Is struct inheritance public by default?

"a struct has public inheritance by default"

Are struct members private 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.

Can struct use inheritance?

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.

Are structs public by default C++?

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.


2 Answers

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.

like image 53
Luchian Grigore Avatar answered Nov 01 '22 06:11

Luchian Grigore


"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 = &dd;

is not allowed.

like image 21
juanchopanza Avatar answered Nov 01 '22 05:11

juanchopanza