C++ Private Structures

49,906

Solution 1

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.

Solution 2

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

Solution 3

One thing that makes this useful is that you can also use the friend key word in structs, so private members can only be used and modified by those specific functions or classes or what not that you want to be able to modify it. This way the user can't modify those sections themselves. They won't even show up in the auto fill features, at least in visual studio.

Share:
49,906
Dasaru
Author by

Dasaru

Updated on March 12, 2020

Comments

  • Dasaru
    Dasaru about 4 years

    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?