|
-
Aug 6th, 2001, 03:52 PM
#1
Thread Starter
Member
Public vs Private (Classes)
I was wondering what is the difference between public and private variables in a class?
Why should i make something private instead of making it public?
Thanks
-
Aug 6th, 2001, 04:16 PM
#2
PowerPoster
Private variables cannot be accessed outside your class but public variable can be.
-
Aug 6th, 2001, 06:24 PM
#3
Thread Starter
Member
Yea, thank you but I know that, maybe I didnt fully express wat my question was. Wy would i want to make the variables private so that they won't be accessed from outside the class, rather than make them public and let them be accessible throughout the whole program.
And what kind of date would i want to keep private and what public?
Thank You
-
Aug 6th, 2001, 06:59 PM
#4
PowerPoster
It is hard to explain but here is what I found:
Declaring methods or data private enables the compiler to find programming mistakes before they become bugs. Any programmer worth his consulting fees can find a way around privacy if he wants to. Stroustrup, the inventor of C++, said, "The C++ access control mechanisms provide protection against accident--not against fraud." (ARM, 1990.)
-
Aug 6th, 2001, 11:43 PM
#5
Frenzied Member
C++ is an object-oriented language, as you can tell since you're using classes. There are several principles in OO design, one of which is encapsulation. You are supposed to encapsulate a class's data within it so that it manages its own data.
The reasonaing behind this is more or less to do with making each class as independant as possible. You provide public interfaces to your class that don't change (these are just public member functions). The interface defines the behaviour of the class and its interaction with things outside it. Then, inside the class, you implement the functionality you promised to provide in your interface, by dealing with privately held data and functions. This way, because you know that nothing outside the class can change what's inside it, you know that any bugs occurring that affect the data inside the class are due to code that is also within the class. By reducing the interdependencies between classes you make your code more managable and easier to debug.
It's almost always a good idea to seperate the interface of something from its implementation, so that you can change the implementation if it's not satisfactory (if it's too slow for example) without affecting the way code outside your implementation calls it: all code using the implementation code has to go through the interface. The interface is like a contract to provide certain services.
Harry.
"From one thing, know ten thousand things."
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|