Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

struct and class and inheritance (c++)

Could you ensure me, if all access specifiers (including inheritance) in struct are public ?

In other words: are those equal?

class C: public B, public A { public:
    C():A(1),B(2){}
    //...
};

and

struct C: B, A {
    C():A(1),B(2){}
    //...
};
like image 667
Grzegorz Wierzowiecki Avatar asked Jun 07 '12 10:06

Grzegorz Wierzowiecki


People also ask

Can a struct in C be inherited?

No you cannot. C does not support the concept of inheritance.

Can struct be used in 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.

What is the difference between struct and class in C?

In C++, structs and classes are pretty much the same; the only difference is that where access modifiers (for member variables, methods, and base classes) in classes default to private, access modifiers in structs default to public.

Can struct types be used within an inheritance hierarchy why why not?

"the reason structs cannot be inherited is because they live on the stack is the right one" - no, it isn't the reason. A variable of a ref type will contain a reference to an object in the heap. A variable of a value type will contain the value of the data itself.


2 Answers

Yes, they all are public.

struct A : B {
  C c;
  void foo() const {}
}

is equivalent to

struct A : public B {
 public:
  C c;
  void foo() const {}
}

For members, it is specified in §11:

Members of a class defined with the keyword class are private by default. Members of a class defined with the keywords struct or union are public by default.

and for for base classes in §11.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.

where the references are to the C++11 standard.

like image 77
juanchopanza Avatar answered Sep 24 '22 14:09

juanchopanza


From C++ standard, 11.2.2, page 208:

In the absence of an access-specifier for a base class, public is assumed when the derived class is declared struct and private is assumed when the class is declared class.

So yes, you are correct: when the derived class is a struct, it inherits other classes as public unless you specify otherwise.

like image 43
Sergey Kalinichenko Avatar answered Sep 22 '22 14:09

Sergey Kalinichenko