1) A get and set function set can help to filter or format values on their way in or out. For example:
1 2 3 4 5
|
void myclass::set_percent(float percent) {
if (percent > 100) _percent = 100;
else if (percent < 0) _percent = 0;
else _percent = percent;
}
|
Or perhaps the value is an output value only and not meant to be set or an input value and not meant to be used for other things.
2) Really the only difference is that classes are private by default and structures are public. Some people will say that structures are deprecated, but I prefer them if there in instances where I just need a few basic types without special constructors, private members or member functions. I use classes whenever I need templates, member functions, inheritances, unknown sized members (like strings) or anything more complicated.
3) A constructor is called when an object is created. Let say that your class will be for network communication. You might use the constructor to open a port and establish communication. The destructor would terminate communication and close the port. It's more intuitive to do this in a function IFF it needs to be done once and only once. Another example would be opening a file for logging. If you are just storing types in a class, then the constructor is an easy way of initializing the class, it serves no greater purpose in that case.
4) See my answer to #3.
5) A little tough to explain. A class' scope is up to you. It could be used to schedule your entire program, by containing a timer callback funciton, an initial function (called by the constructor) and a iterating function called every X milliseconds by the callback function. It could also just contain someone's name and employee number, then be used an an array to keep the values togeather and associated.
6) let's say that you are simulating a car. You might program the properties of a tire. The elasticity, how it can handle torgue, the friction during braking, the tread wear/life, etc. Now a car has 4 tires, so are we going to write 4 versions of each function and of each parameter of the tire? No! What if a tire falls off, it would be a mess to code! In object-oriented programming we would program the properties of only one tire, then use it over and over as an object. If our car has 5 tires, then we just create 5 objects of the tire class.
If it's a multi-engined aircraft, we only need to program one engine, then make more instances of it. If we are programming a restaurant, we would only program one glass and then make many copies of it. We could also program a few different types of glasses: wine glasses, beer glasses, champaign flutes, coffee mugs, etc. All of these would have something in-common: They can all hold liquid. Therefore we could program that property only once and then all of these containers could inherit that property. Now it starts to get deeper.