CS 102 Lecture Notes
Week Five, Monday/Tuesday: Classes, Part II (cont.)
Dynamic Memory Allocation with Operators new and delete
In writing C programs you might have become familliar with the malloc
function for allocating heap memory and the free function for giving the
memory back to the operating system. C++ allows the use of the new
and delete operators which are easier to use (but accomplish the same
purpose).
static Class Members
Use the static keyword to have various instantiations of a class
share data. Use this feature cautiously because it introduces data coupling
among objects and make programs harder to understand.
Container Classes and Iterators
Container classes are also sometimes called "collection classes." Examples
include arrays, stacks, queues, trees, and linked lists. Container classes
provide services such as insertion, deletion, searching, sorting, etc.
An "iterator" is an object that returns (or performs some action on) the "next" item
of a collection. Iterators are often declared as friends of the container
class for performance reasons (a friend function can avoid the function call
overhead by directly accessing member data).
Object Model Demo Program
I have created a
small demo program
to illustrate a container class using the example of bonsai. The source is in
a single file for convenience because it's a minimal example program. The class
Bonsai uses an array of Tree object pointers (a single bonsai has one pot
and one or more trees). Using this pointer array technique, the trees can have
knowledge of which bonsai they are associated with (and the same with the pot)
by using a "void pointer" member data type.
The test program (an automated test sequence (ATS)) creates some trees, pots,
and bonsai in order to exercise the various features of the model:
// Construct some trees, pots, and bonsai for test:
t1 = new Tree("Gnarly Old Oak", "Cork oak");
t2 = new Tree("Curvey Old Oak", "Cork oak");
t3 = new Tree("Straight Old Oak", "Cork oak");
t4 = new Tree("Ancient Juniper", "Prostrata juniper");
p1 = new Pot(16, "Oval", "Brown", "China");
p2 = new Pot(13, "Rectangular", "Gray", "Japan");
b1 = new Bonsai("Cork Oak Forest");
b2 = new Bonsai("Venerable Shokan Juniper");
When run, the program outputs the single screenful of text as shown below:

Runtime session for the object model demonstration program.
For demonstration purposes, I had the Bonsai class destructor output the
string " *kaboom* " to indicate the running of that function.
This page established September 18, 1999; last updated Jan 17, 2000.