Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Availability of private and protected in C++ structs

Tags:

c++

c

Can we use access specifiers - private and protected - in C++ structs (as opposed to classes)?

Also, do access modifiers exist in C?

like image 687
Priya_fsr Avatar asked Mar 25 '13 14:03

Priya_fsr


People also ask

Do structs have public and private?

A struct can indeed have public and private sections, member functions as well as member variables, and special functions such as constructors, destructors and operators.

Can structs have private methods?

Yes structures can have private members, you just need to use the access specifier for the same. struct Mystruct { private: m_data; }; Only difference between structure and class are: access specifier defaults to private for class and public for struct.

Can we use access specifiers private/public protected with structures in C?

Can we use access specifiers - private and protected - in struct of c++? Yes.

Can a struct have private members?

Class members, including nested classes and structs, can be public , protected internal , protected , internal , private protected , or private . Class and struct members, including nested classes and structs, have private access by default.


2 Answers

C doesn't have C++style access modifiers. A C struct is just a composite object type containing members of other object types.

In C++, a struct and a class are almost identical; the only difference is that struct members are public by default, and class members are private by default. So this:

struct foo {
private:
    // ...
};

is equivalent to this:

class foo: {
    // ...
};

This has been answered elsewhere.

This implies that the private, public, and protected keywords are equally valid in either a struct definition or a class definition.

As a matter of programming style, on the other hand, if you're going to be using access modifiers, it's probably best to define your type as a class rather than as a struct. Opinions will differ on this, but IMHO the struct keyword should be used for POD (Plain Old Data) types, or for types that could be defined as structs in C.

C++ structs, strictly speaking, are very different from C structs, and are nearly identical to C++ classes. But if I see something defined in C++ as a struct, I expect (or at least prefer) it to be something similar to a C struct.

like image 186
Keith Thompson Avatar answered Oct 30 '22 20:10

Keith Thompson


In C++ a structure is the same as class with the only difference that the default scope is public unlike private that is the default scope for class. In C access specifiers don't exist but after all what would you use them for?

like image 41
Ivaylo Strandjev Avatar answered Oct 30 '22 20:10

Ivaylo Strandjev