Question:
Why have "Private" fields inside a C++ class?
JamES
2013-02-27 22:17:42 UTC
Can someone please try and explain to me why within a class (C++) you would normally define a group of fields (variables) that are private? I don't understand this concept.

Is it so that those fields (variables) cannot be modified from outside the class?

I still don't fully understand why you would need this feature, can someone explain it to me?

So can you give me an example whereby a struct should be used (or would be better suited) than a class would be?

Thanks kindly,
James
Eight answers:
llaffer
2013-02-27 22:27:17 UTC
The best way that it was explained to me when I was confused about this was something like this:



When you start to get into larger programs with multiple classes all talking to each other, generally when working on a team, someone will be responsible for one or more classes and everyone else has no control over what they are doing.



So one way to "protect" their own classes from accidental (or purposeful) misuse of data in your class is to make the data directly inaccessible by making them private and using public "getters and setters" to receive and set the information into the private data. This ensures that you have full control over what data goes into the private variables of your class. If someone calls a setter with data you don't like, you can simply reject it. If that other class has direct write access to your data, then someone else could put bad data in to your class and bad things could potentially happen as a result.



You have one last chance for some error checking before data gets saved into your class.
michaeljhuman
2013-03-01 14:01:53 UTC
There are two questions. The reason for private has been answered in many ways already, so I won't answer it.



In C++, struct is 100% identical to a class, but every member is public by default. This is almost certainly done to make old C code, which used structs work in C++. They could have put further restrictions on structs to make them more like C, but there was no point.



A class and a struct are then pretty much the same thing ( pretend a struct is a class that starts with public:)



It's Annoying with a capital A to use private and protected members. You are always having to change them up, or add public versions to allow outside access. Python, and other languages decided they are not worth the trouble.



HOWEVER, in large projects especially with multiple programmers, they enforce proper programming practices. You force outside clients (users) of a class to use only those functions approved for external use. This can avoid many nasty issues.



C++ is adding getters/setters similar to Java, which could eliminate some of the annoyances with private data while maintaining proper "encapsulation" of the internals of a class.



Hope this helped. Some of the answers were good, but long. Probably because there's so much theory on object oriented programming which was behind the decision to have private, protected and public modifiers.
2013-02-27 22:38:47 UTC
So, in other words, what's the benefit of object oriented programming?



You're looking at this from the point of view from someone who's just getting started. If you're the only person who will ever use your own code then the scope and visibility of variables is less important. But in, let's say, the corporate world, you may write a class that other programmers will then use. It's your job to make sure the class doesn't crash the program.



If your class' variables are all exposed and I write some really bad code that uses your class I might make your class crash. Let's say you have a class that requires a persons name, and it stores that name in a database. I might wright some bad code that sets that variable to "Fred Mc'Dowell." Well, if the database you write that name to is SQL, then that name will cause an error - SQL uses single quotes ( ' ) to identify strings, so when the SQL parser sees the single quote it will expect the end of the string, not the word "Dowell".



As the writer of the class responsible for saving data into the database, it is your responsibility to ensure that the data you write is legitimate. Therefore, if you want your code to behave well and not cause bugs, you will want to make the strName variable private, and use a Set Property function to control what goes in there. You might write code to look for invalid characters and strip them out, or you might simply not accept the bad input, and instead return an error code so that the programmer using your class has to fix the problem on his end, and it doesn't become your problem.



That's the primary benefit of encapsulation - hiding your internal variables and functionality.



As far as using a struct, one issue is what I just said. Another is that you can have functionality in your class, and you can't have it in a struct. For example, your scheduling program might let the user enter start-time and end-time. Let's say you want to have the appointment length calculated once and stored at the time of data entry, rather than recalculating every single time you want to display it. A Struct won't do that for you - you'd need to write the code to calculate it. But your class could automatically determine that data and store it as part of itself. TimeEnd - TimeStart isn't complex, but things can get a lot hairier.



Struct is the predecessor to classes. Before classes existed, people used structs for managing sets of associated data, so your question is exactly on target. If you want to store associated data together without the need for associated functionality then a struct might be all you need. For example, if you are plotting points along a curve, maybe the only data you need are the X and Y coordinates. You could use a struct to store each pair of coordinates or pass them between functions.
2013-02-27 22:32:17 UTC
First off, let me say that although this question is easily found on google...this type of question is probably one that many people have, and would benefit from hearing about someone has both education and experience in the field. Good question.



Okay...at little theory first.



Go here, http://dictionary.reference.com/browse/paradigm?s=t



Look at definition number 2. So...what does mean in computer science terms? Well there are two very well known paradigms that are in use today. Top down and object oriented.



The top down paradigm basically means that you build fully functioning modules by reducing the number of steps in your program though use of an algorithm. Each function should do only one thing, and you use the main program to control them.



Now...object oriented, expand on this concept. Yes, you still use functions, but in a very different (but similar way). You still reuse the same concept of functions...but you have a bunch of added stuff that you can use to improve the functionality (templetes, method overloading, abstract classes/virtual functions/interfaces). The job is to move from making each module a function...and "give it life". You model classes after real world concepts, and each class should have data fields (in OOP terms we these data members) and functions (in OOP terms we call these methods).



So...now lets start getting more technical.



Do you know what a struct is? Think about a second....



A struct is a "data structure" right? So...why is all the data in a struct declared as public? Well...this is a very dated version of encapsulation (one of the three main concepts of OOP...which are inheritance, encapsulation , and polymorphism). What happens if you declare the fields as private? Try it.



You can't access the data..can you? Did you get any compiler errors?



Well...lets expand a struct to include functions. We'll call this a class. So...what is a class? It's a data structure with functions. Now...we need to apply the concepts of OOP to this. So...we want to make functions have just what they need (inheritance), keep data private from things that don't need to screw with it ( encapsulation ), and make the function "generic" enough to change though subclasses if we need to (polymorphism).



Now, to answer your question.



There are three types of inheritance (also the access specifiers)...public, private, and protected.



In public inheritance...anything can access the private things (what is usually only data).



In private inheritance...the only things that can change the private fields are public things.



In protected inheritance...the only things that can change the private fields are public things (the same as private)...BUT....this stuff gets set as private if you declare a subclass.



So to actually answer your question, you use it because it follows the OOP guidelines, and for that reason only. You make public methods and use them to change the data in the private fields (gett and setter methods) You could in theory do the same thing with protected data members (use public stuff to modify the protected stuff)...but "many" claim that this breaks the concept of encapsulation as is discourages...but it's up to you to deteremine when to use this (I wont tell!)
Cronin
2013-02-27 22:26:32 UTC
With classes you really don't need structs.



see the below wiki link about encapsulation. Here's a quick example... you are a bank and you have a class that has an account balance and methods for withdrawing or depositing cash. The deposit and withdraw methods verify cash so you can't fool them. You can only make a withdraw if the account balance is positive and greater or equal to the amount you're trying to remove.



Now, if a client uses this class, should the client be able to withdraw unlimited amounts of money?



if the account balance isn't private he can change the value at will without going through the deposit or withdraw methods. This isn't good. If the data member is private then the client cannot change the value.
2016-03-08 10:49:46 UTC
Haha funny. Suspension is ridiculous, it's not a particularly inappropriate name really. Anyone that thinks it is must be out of touch with the times because I live in a pretty upscale neighborhood and there was still a bunch of kids saying crazy crap like that and cuss words even elementary school so it's not like they haven't heard it before. I do agree with the teacher that it would have been wise to use the initials though. Maybe not letting you play and then a stern talking to... no real ramifications should have been necessary though. Also, just a bit of constructive criticism, I think "math class orgasm" would sound better as a name than " orgasm in math class". It just rolls off the tongue better and it's still unique and memorable, which is important for a band name.
2013-02-27 22:24:37 UTC
in object orientation concept you can specify an object from a class so when you make an object from the class you also make an instance (like a copy) of all variables ,enumerators, struts ,pointers, methods, properties everything in that class. so a copy of all aforesaid things are now within the newly made object. now you can use this object to access to all variables ,enumerators, struts ,pointers, methods, properties. but let's say you don't want other people to access to some of variables ,enumerators, struts ,pointers, methods, properties. then you can protect them so they can't access to them. to protect them you can use the private and it's known as access modifier. if you want them to access then use public and this overall thing is known as encapsulation. encapsulation is mostly used in the business field to protect the business secrets like special algorithms or some other secret codes that can be used to decode the file types so other people can read it.



.
2013-02-27 22:21:24 UTC
Encapsulation. So that the interface methods are the only means to pass vales to and from the objects created from a class.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...