Example C++ classes for CGI processing
Processing the pizza order

The code defines two classes: class FredsPizza and class FredsCGI.

The FredsPizza class defines a smart data structure. It has data members that correspond to each of the fields in the pizza order form, and some extra members used when computing things like the cost of the pizza. Most of these data members are strings. Things like multiple topping options are handled by concatenating the descriptors together to form a single long string (more typically, you would need an array or list when you have to handle multi-choice selection elements).

The constructor initializes data members, the destructor frees any allocated strings. The member functions that "set pizza size", "add a topping" etc, update the values in data members and maintain counters.

The FredsPizza structure also gets responsibility for generating much of the response page, and for writing data to a log file.

The only complexity in the FredsCGI class relates to file handling. This CGI program logs orders to a file; so it opens a file in append mode (new data will be written at the end of the existing data) and then, via the FredsPizza::log() function writes several lines to that file.

If this Pizza cyberparlor were to prove popular, you might end up with two or more instances of the pizza CGI code running in different processes. Each would try to append data to the file, with a high probability of interleaved write operations that would corrupt the recorded data.

The first instance of a CGI program must acquire a lock on the file and hold this lock until it has written all its data. The operating system will block any second process that asks for the file until the lock is released. The locking of the file is illustrated in the constructor and destructor for the FredsCGI class.

The FredsCGI class has to define effective implementations for the StartTokens, EndTokens, and ProcesToken virtual methods in the base CGI_Helper class. The redefined functions print an appropriate header and trailer for the pizza order response page, and arrange to invoke an appropriate data recording method of the FredsPizza object as each token is processed.

The main function simply instantiates a FredsCGI object, and runs its header generation, request processing, and trailer generation functions.