Is it true that methods in one class can only operate on the members of that class? |
Nope. Static members don't even require a class variable/instance to be used. but you can certainly operate only off parameters just like anything else. This may be a dubious design most of the time ... there are a great many things you can do and probably usually wouldn't in both C and C++.
class c
{
static int duh(int x) {cout << x*42 << endl;}
}
...
c::duh(3);
c obj{};
obj.duh(4);
Can methods created outside of a class reference public members of a class directly |
Sort of. Remember that in c++ a class is a TYPE (in C its a weird grouped variable created on the spot that has to be FORCED into acting like a type). It makes no sense to try to modify a class variable directly because its a part of a type, not an existing variable. A static class variable can be treated this way, but note that the value is the same for ALL instances, one variable, shared across all. You can certainly modify the public variables of a variable of type someclass 'directly' though, as in x.variable = value;
The get set methods are recommended by many. In some cases it is eggheadery, protecting yourself from yourself and sort of idiotic for smaller programs where it brings nothing to the table except a bulk ton of clutter. There are 2 big (real, not just OOP theory) reasons why its done:
1) when the getters and setters DO something besides get and set. This can be a layer of protection, like returning a copy of the value (which can be modified without affecting the original), or like validation for the case of input/modifications, whatever.
2) consistency. It is highly likely in a large program you will have #1 above for some values. At that point, you can either have a 'guess which way' set of objects where whether something has a getter/setter depends on the value and the whim of the developer, or you can sigh at the mess and put one on everything. Even microsoft got irritated with this: many of their MFC objects actually have BOTH direct access to the values AND functions to do the same, specifically their point/rectangle/etc gui positioning stuff has a dozen ways to change just a couple of values.
there are also 3) and 4) which are less practical and more theoretical... encapsulation and data hiding ideas (and there may be a 5, 6, 7.. as well, its been a long time for me since I dealt with the theoretical design stuff) which do have practical applications, but as often as not, its just 'because someone said so' for a specific design -- the things they are solving are non-issues more often than not.