Tuesday, March 24, 2015

Post #14 - first look at classes/objects

Lot of catching up to do here, eheh... Here's a simple demonstration of a class. A class is like a function inside of a function, it makes your code very condensed so more work is put into the general goal/purpose of the program rather than in what each function or variable is doing in the background. The background work is handled by the class's member functions. I like to think of it as a kind of castle or house - outside of the castle, there is public property and anyone can access whatever things lay outside the castle walls. However, anything inside the castle is private property, and only the members of the castle can access these things. Friends of the castle inhabitants must ask them first if they can use anything inside the castle, and cannot access things inside the castle directly without permission from the members. In program terms, a class has two permission groups - public and private. Variables and functions can be inside either group, but private variables and functions can only be accessed through the class's public member functions. The private group has content only known to the class, and this content (variables, functions, etc) can't be accessed without a call to a public member function that handles that content.
In the programming example above, Queen()and King() are member functions of class KINGDOM. They are public, meaning that outsiders know of their presence and that the royalty can communicate with others outside of the Castle, the object that is called with its member functions before main. However the castle's treasure of gold and silver is private - it's safe to keep your valuables hidden, after all. The queen knows how much silver and gold is stored away (5 kg and 9.9 kg), and assigns these numbers to their respective private variables. The king uses the same variables to tell the rest of the "public" (i.e. the rest of the program not part of the Castle object) how much of each the castle has. However, the amount of each within the castle cannot be modified by outsiders once their amounts are set, because they are stored as private, not public. If the values needed to be changed, a new member function would have to be created to re-assign new values to silver and gold, the queen can initialize them with different values, or the queen can be passed values set by the main program since Queen() is a public function of the class (via initialization, user input, or data read-in).

The resulting output is as follows:
Kingdom treasury: 
Silver = 5 kg
Gold = 9.9 kg

Using classes and objects can obviously neat-ify programs, and tracing exactly who does what at a specific point in main is made easier by public member functions that can access private variables so their data isn't altered inadvertently by main.

No comments:

Post a Comment