CS12, Lab 8

Week of March 5-9

 

 

Topics: 

·        Inheritance

·        Base classes and derived classes.

 

 

 

Background:

 

From the Counter class, we can derive another, more specialized class, which is essentially a counter with bells and whistles. Objects of the derived class, MemoryCounter, perform all the same operations as a counter (initialize, increment, and getCounter), along with two others -- the MemoryCounter object keeps track of the number of times the counter was initialized, and of the total number of times the counter has been incremented, regardless of initializations.

 

The total count is stored in the data member totalCount. The number of initializations is stored in a data member numResets.

 

The derived class has two new accessor functions, that reurn the values of these data members. In addition, the derived class will have to override the base class method initialize(), to keep track of the number of initializations that the counter goes through, and to add the current value of count to totalCount before resetting it to zero.

 

Please note: Only the initialize() method is overridden. While it is possible to override the increment() method to keep track of the number of times it was called, it is more efficient to update totalCount only when initialize() is called instead of every time increment() is called (the assumption is that increment() will be called many more times than initialize())

 

 

 

To do: 

·        Create a directory and place in it the files counter.h and counter.cc. Change the private: label in counter.h to protected:.

·        Download the files mcounter.h and mcounter.cc. They include the header and shell for the class MemoryCounter, which is derived from the Counter base class.

·        Write the methods getNumResets() and getTotalCount() for the derived class.

·        Override the initialize() method in the derived class to keep track of the number of initializations and the total count.

·        Write a main() that declares a Counter object and a MemoryCounter object. Perform the following operations on both objects (cut-n-paste works great): increment the object several times; print its value; initialize; increment a few more times; print; initialize; print; increment several more times; print. Note that the values printed should be identical for both objects. If they are not, something is wrong with your classes or your program.

·        For the MemoryCounter object, print out the number of initializations (should be 2), and the total count (should be the number of times increment() was called). What happens if you try to invoke these methods with the Counter object?