Can we use access specifiers - private
and protected
- in C++ structs (as opposed to classes)?
Also, do access modifiers exist in C?
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.
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 and protected - in struct of c++? Yes.
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.
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 struct
s 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
.
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?
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