Sample Code
Sample Code from CSS 342
An example of well-documented code using pre and post conditions:  
array.h    
array.cpp    
Driver to test the code:  
arraydriver.cpp    
Inheritance, Point <-- Circle <-- Cylinder:      
sample main
Point ...
       
point.h
       
point.cpp
Circle ...
     
circle.h
       
circle.cpp
Cylinder ...
 
cylindr.h
     
cylindr.cpp
Inheritance examples:
Simple example using inheritance ... consists of a base class
(Fruit) and
three derived classes (Apple, Orange, Grape).  
There is a linked list of Fruits.
The items start out as specific Apples, Oranges, or Grapes,
then become Fruits in the list.
Inheritance allows the objects to define their own functionality
when virtual functions are used.
Fruit UML diagram
The print routine is virtual.
Virtual "print" is used for Apple and Orange.
Grape has no "print" routine, uses "print" of Fruit.
The code:
fruit.cpp ... with output:
output
The print routine is NOT virtual.
All child classes have "print" but because it is not virtual,
the "print" of Fruit is used for all.
The code:
fruit.cpp ... with output:
output
The print routine is pure virtual.
All child classes must provide an
implementation of "print" and it is used.
All the code:
fruit.cpp ... with output:
output
A better fruit example.
Fruit is an abstract base class.
Fruit and List have destructor and copy constructor.
Fruit has a virtual destructor and a pure virtual method, clone,
so the copy constructor will copy correctly.
The copy constructor and destructors print so you can follow execution.
The code:
betterfruit.cpp ... with output:
betterfruitoutput
Create new objects through a hash factory
(Wrapping a function in an object is a Functor; in this case the function
creates objects)
(An array/hash table of these create functions produces a Factory):
UML ...
hashfactory.cpp ... with ...
output
Static vs. dynamic casting.
Static cast:
caststatic.cpp ... with output:
caststaticoutput
Dynamic cast:
castdynamic.cpp ... with output:
castdynamicoutput
Private inheritance - everything is inherited as private
Override to public:
inheritPriv.cpp ... with output:
inheritPrivoutput