Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Private Structures

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?

like image 591
Dasaru Avatar asked Dec 10 '11 05:12

Dasaru


People also ask

Can C struct have private members?

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".

Can struct be private in C#?

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 .

Can you use private in 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: access specifier defaults to private for class and public for struct.


2 Answers

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
  • inheritance defaults to private for class and public for struct

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.

like image 125
Alok Save Avatar answered Oct 23 '22 13:10

Alok Save


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).

like image 41
bdonlan Avatar answered Oct 23 '22 15:10

bdonlan