1. Classes
    1. Foreword
    2. Microwave oven
    3. Basics
      1. Visibility
      2. Class General Design
      3. Constructor
      4. Params
      5. Default values
      6. Destructor
      7. Member function Defenition (.hpp-file)
      8. Member function Code (.cpp-file)
      9. Const or not
    4. Usage
      1. Member Functions
      2. Return reference to object
    5. Pointers
    6. Example class
      1. Open File var.hpp
      2. Open File var.cpp
      3. Use the class
    7. Subclassing
      1. Example

Classes

Foreword

Since Adrian wrote about strings I've decided to continue from there and build a string class futher down. The example contain hands on code for e.g. pointers, operators etc. to show how to include and use them when designing classes. A class is a collection of useful variables and methods with the tools that can alter objects. Leave all the manipulation of the object to the class itself and forget how to deal with pointers, memory, tweaks etc. for every part of the app just to ensure that it will work.

Microwave oven

Just as a microwave oven is built up from simpler parts like circuitry, screws, fan, wiring, leds etc. the class should use simpler variables (int, char, double etc.) or even other classes or objects etc. (string...) to form the more complex object (microwave oven) that suite the needs best. The one that will use the class shouldn't have to know about the internals of the class, just as we don't have to care about how the microwave oven heat the food, as the complex parts should be disguised and simplified by our class. Encapsulation and improvement of complex objects is one goal, simplifying the use another, but it's very important to not remove functionality in the design process of the class. Variables should be hidden to the user, as much as possible, while methods should take care of how to manipulate functionality so that the class is easy to use yet powerful. Don't just write classes or function to solve one specific problem ... try instead to make it general so you or someone else can reuse it later.

Basics

Visibility

To hide the internals of the class there's private, protected and public sections and just as it sounds they behave different depending on the use. Private variables and methods are private to the class itself, while public expose such things to the user. See table below and the course book for a more in-depth explanation.
Visible to public protected private
User Yes No No
Derived class (Subclass) Yes Yes No
Member functions and friends Yes Yes Yes

Class General Design

The design of a class is very similar to a struct but classes add alot more than a collection of variables, something that we also can get with variables placed in the public section of a class. A good design strategy is though to place variables in the private section of the class, so that one can control access and ensure that no problematic data will be added. Helper functions that shouldn't be available to the user but only to the class itself should be placed in either the protected or private section as well. All other functions and useful methods should be added to the public section, but it's up to the designer to decide what features should be added and how to check for errornoues input data and how to handle such things.
class Class_Name {
private:
// List of class attributes (variables, types, constants and so on) that are intended to to be hidden for reference from outside the class.
// List of prototypes for each member function intended to be hidden from outside of the class.
...
protected:
// List of class attributes (variables, types, constants and so on) that may be accessed by name from derived class but hidden from outside the class.
// List of prototypes for each member function 
may be accessed by name from derived class but hidden from outside the class.
...
public:
// List of class attributes (variables, types, constants and so on) that may be accessed by name from outside the class.
// List of prototypes for each member functioon that may be accessed from outside the class.
...
}; // Note that a class definition has to end with a ; (semicolon)

Constructor

To create the object from the class we intend to write we need to have a constructor that will initialize all variables and allocate memory enough to hold data. A default constructor take no parameters but initalize variables anyway and it has to be present in the class in the public section with the same name as the class itself.
Class_Name() {
   alloc_size = 256;
   // Set default values for variables in class ...
}; //Note the additional ; (semicolon) here

Params

Sometimes it's very handy to or even a must to set params during allocation and creation of the object. As alternative for integer, double, long etc. as mentioned above it's possbile to set values after the paranthesis to the right of : (colon), additional parameters should have , (comma) set in front.  There's no need to have parameters in the call to use e.g. alloc_size( 256 ) below, it could have been used in the example above as well.
Class_Name( Param_1, Param_2 ) : alloc_size( 256 ), width( Param_1 ), Length( Param_2 ) { ...

Default values

By using default values as we learnt when we wrote functions it's possible to write one version that can handle different needs, it's even sometimes possible to make everything default. Be careful though which order to place the parameters as default ones can't be placed before (to the left of) mandatory parameters and that some variables is more useful and will be used more frequently than others. If all parameters can have a default value set, then the constructor can act as a default constructor too.
Class_Name( Param_1, Param_2 = 10 ) : alloc_size( Param_1 ), items( Param_2 ) { ...
Note 1: Not only variables with default values can be set like this.
Note 2: Arrays of data, usually pointers can NOT be set this way.

Destructor

With the same reason we need a constructor we a destructor too, that will destroy the object and return memory back to the system when the application end or when the object will no longer be used. A default destructor is always provided unless you write your own, but it's useless if you use pointers and more sofisticated designs.  Add your own if needed in the public section.
~Class_Name() {
   // Delete variables, clean up and return memory to system ...
}

Member function Defenition (.hpp-file)

Define what is possible to do with the class in the public section.
return_type method_name( Params ); // Comment

or create a method that is a friend if the class, it should contain a member function that doesn't involve variables in the class object.
friend return_type member_function_name( Params ); // Comment

or if the class should provide operator for easier usage.
return_type operator = ( Params ); // Comment

Member function Code (.cpp-file)

The code for the defined methods should then be placed in a separate file with the same name as the header file. Write the methods as normal functions, but remember to adjust them so that they appear as part of the class.
return_type Class_Name :: member_function_name( Params ) {
// Function body.
...
}

or for the friend member function
return_type member_function__name( Params ) {
// Function body.
...
}

or for operator
return_type Class_Name :: operator = ( Params ) {
// Function body.
...
}

Const or not

If the object or variable in question must not be changed by the method it's common practice to add a const to the type. The function below take one parameter which can't be alterd, but it also doesn't alter the object itself, so therefore it's possible to set the whole method as const in the end as well.
return_type Class_Name :: member_function_name( const Param ) const {
// Function body.
...
}

Usage

It's quite easy to use a class if it has been designed well, just include the header file and create the object the same way as with int, double etc.
The main difference is that it's possible to use the member methods to get and set data instead of accessing the variables directly. Carefully written methods take care of problematic calls and minimize coding quite alot at times.

Including header file:
#include "header_file.hpp" // Include the header file just as usual

Creating the object:
Class_Name Name_of_Object( Params );

e.g. call the default constructor that create the object and allocate necessary memory to the hold object.
Class_Name MyFirstObj;

or call a custom constructor that can take parameters needed to create the requested object and allocate the right amount of memory.
Class_Name MySecondObj( Params );

If the constructor has been designed carefully, it's possible to let the custom and default constructor be the same.

Member Functions

The functions inside the class is referred to as "member functions", that's because they manipulate the object created from class.

To manipulate the object just call the member function that's appropriate with the parameters needed.
Name_of_Object.member_function( Params );

Some of these member functions return values or similar, but that's just as usual ... e.g. use another variable to store that return value in.
Let's assume that the class that the object MySecondObj has been created from contains a member function toInt that take no parameters but return the integer portion/interpretation of the object defined by the designer of the class. The resulting call could look something like below.
int value = MySecondObj.toInt();

Some of the member functions use other member functions to manipulate the data, since it's a member function that calls another member function there's no need to specify which object it will work on as a hidden pointer to this is provided automtically.
return_type member_function( Params ) {
// Function body.
AnotherMemberFunction( Other_Params );
// ...
}

Return reference to object

One useful feature to add to classes is to return a reference to the object itself (reference to *this) when a member function ends, even though there's no obvious need to return anything, also note that it's only useful when there's nothing else to return. With a reference like that it's possible to call many consecutive member functions right after each other and not only call and write them on may rows.

Let's assume that the same text has been added to both objects, MyFirstObj and MySecondObj and that the class contain mentioned member functions.

MyFirstObj.upper();
MyFirstObj.split( 120 );
int i = MyFirstObj.boyerMooreSearch( "Needle in Haystack" );

and compare the call to
int i = MySecondObj.upper().split( 120 ).boyerMooreSearch( "Needle in Haystack" );

The latter method can in some situations be very useful and it doesn't add much code to each member function (return *this;) either and it's still possible to call them as in the previous example. Functions that doesn't return a reference to the class/object can't be used to call other member functions as the reference are set to something else then (int, double, void etc.).

Note that the objects MyFirstObj and MySecondObj has been alterd compared to what they started with (upper case and splited) as the member functions used change their contence.

Pointers

Classes can be very useful if you want to create objects that takes care of the problems with pointers, but remember that for every new there has to be one delete when you allocate a *variable.

Example class

The name of the class is var because it can handle both text and values (int, double and long) transparently so the user doesn't have to take care about pointers, memory allocation or conversion. The class store the main data as a pointer to an array of characters with the addition of a value for the number of characters the array hold and another to indicate wether the array should resize dynamically or not. The "s" added can do most everything to the string but also handle data types that is common to encounter. Among other things there's a version of the efficient BoyerMoore text search algorithm, substrings manipulation of different kinds etc. but also operators like + (addition), - (subtraction), * (multiplication), / (division) that can handle both text and numbers. There's no useful member function corresponding to * (multiplication) of text yet, but if anyone can present and write a useful enhancement...

var.hpp

Contains the variables, member function definitions and not so much code, this file should also contain comments that give a meaningful description of the member functions provided. Main purpose to the user of the class is for reference how and what the different member functions work and how to call them.

var.cpp

Contain the code that perform the tasks. User of the class should only  have to look at this class if there's special need to understand the underlying tasks that the author of the class has failed to describe in the header file.

Use the class

#include <iostream.h>
#include "var.hpp"

int main() {
  var i, j;
  var string1( "This is a sample text to test the class" ), Variable2( "your knowledge" );
  i = 1;
  string1 = i + ". " + string1; //1) What would the result be from a call to cout at this point?
  string1.leftOf( "the" ).cat( Variable2 ); //2) What would the result be from a call to cout at this point?
  j = i + 0.56 + string1; //3) What would the result be from a call to cout at this point?
  return i; //4) Which member function is most likley to handle this?
}

Subclassing

Subclassing (Superclass) etc. is a very useful way to extend and modify behavior of classes as well as reuse code and features. The idea is to use the excisting class and wrap it with new and improved features to extend and improve it's use. 
class SubClass_Name : private Parent_Class {
// Class definitions etc.
...
};
Note: Private causes the parent class to be visible only to the subclass and not available to the user as seen in the table.

Example

Vehicle is a common word for a machine that transport 1 or more person(s) from position A to B.

Bicycle is a Vehicle without engine but with 2 or 3 wheels used for transportation of 1 person and/or small amount of cargo.

Car is a Vehicle with engine and 3 or 4 wheels used for transportation of 1 driver and up to 6 passengers and/or cargo and/or combined with a trailer with a total weight less than 3 500 kg.

Bus is a Vehicle with engine and wheels on 2 or 3 axels used for transportation of 1 driver and more than 6 passengers and/or with a weight of 3 500 kg or more. Can be combined with a trailer but must not be longer than 24 meters together.

Truck is a Vehicle with engine and wheels on 2 or 3 axels used for transportation of 1 driver and up to 6 passengers and cargo with a weight of more than 3 500 kg. Can be combined with a trailer but must not be longer than 24 meters together.

etc.

From the description above it's possible to draw something similar to the simplified hierarchy described below. Some parts have been left out deliberately as it otherwise would take to much space. The Vehicle class contain basic data and methods that is common to all types of vehicles, while the subclasses Car, Truck, Bicycle, Motorcycle, Bus etc. add features common for their respective categories.
Vehicle
Car Truck
Cabriolet Sedan SUV Hatchback Station Wagon Freight Truck Lorry etc.

1) Name the variables to hold the neccasary data and methods to manipulate them from the text above to describe Vehicle.
2) Name the methods that has to be rediefined for a subclass Car.
3) Name the variables and methods that has to be added to a subclass Car.

to be continued...?