Private access members are accessible only to other class members, not objects.
Example:
#include <iostream> class MyClass /* ww w . ja va2s. com*/ { private: int x; // x now has private access public: void printx() { std::cout << "The value of x is:" << x; // x is accessible to // printx() } }; int main() { MyClass o; // Create an object o.x = 123; // Error, x has private access and is not accessible to // object o o.printx(); // printx() is accessible from object o }
Our object o now only has access to a member function printx()
in the public section of the class.
It cannot access members in the private section of the class.
If we want the class members to be accessible to our object, then we will put them inside the public: area.
If we want the class members not to be accessible to our object, then we will put them into the private: area.
We want the data members to have private access and function members to have public access.
This way, our object can access the member functions directly but not the member fields.
There is another access specifier called protected: which we will talk about later in the book when we learn about inheritance.