I have read that the main differences between classes and structures (other than functions), is that class members default to private, whereas structure members default to public.
That implies that structure members can be private. My question is: Can you have private structure members? And if you can, what is the purpose of using private members? How would you even access them?
Sometimes a question arose "Can a structure has private members?" The answer is "Yes! In C++, we can declare private members in the structure". So the important thing is that "we can declare a structure just like a class with private and public members".
Struct members, including nested classes and structs, can be declared public , internal , or private . Class members, including nested classes and structs, can be public , protected internal , protected , internal , private protected , or private .
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.
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:
How can you access them?
Just like you access private members of a class. i.e: they can only be accessed within the structures member functions and not in derived structure etc.
The only difference between struct
and class
is default access (with the exception of some weird template situations, see Alf's comments below). This means you can access private members in the same way as in a class:
struct foo { int get_X() { return x; } void set_X(int x_) { x = x_; } private: int x; };
Whether you use struct
or class
, then, is purely a matter of style. I tend to use struct
when all members are public (eg, if it's a functor class with no member variables and only public functions).
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