Why use "private" in c++ classes? What's the point?

I'm trying to get the hang of classes. I understand the need and use of "public:" in classes, but I do not see the need for the "private:". I know private is for private objects that can only be accessed by member functions under public:, but why not just dump all those private variables in public: and eliminate the need for private:

Am I missing something? Because I think I am.


And does anyone know any good online tutorials for classes, structures,constructors,operator overloading.

-greatly appreciated.
I guess for security. Think of an engineer who makes a car vs. a person who buys a car to use (and knows nothing about cars). The engineer does not want the person who bought the car to mess around with the insides of the car and possibly break something. As a programmer creating a class you want the person utilizing the class to work through its interface, not mess around with its insides and possibly cause errors.

For example, if you have a String variable str that is public, someone using the class can just say str = 5, this will cause an error and the program to crash. But if str is private and you have a public member function setStr(), you can handle errors properly in the function. So if the person using setStr() try's to set String str to an int you can print them a message such as: "invalid input try again", instead of crashing the program.
Last edited on
I think we have a pretty good tutorial on the subject ( http://www.cplusplus.com/doc/tutorial/classes/ ) //EDIT: whoops wrong link before :P

The other real big use is with inheritance, when you have something under private then the classes that are derived from that class don't end up having any of the private members; they will however end up with any protected members in case you need inheritance and still want security as mentioned above.
Last edited on
Topic archived. No new replies allowed.