C++ Private Structures

Dasaru picture Dasaru · Dec 10, 2011 · Viewed 41.1k times · Source

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?

Answer

Alok Save picture Alok Save · Dec 10, 2011

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.