CS 102 Lecture Notes

Week Two, Wednesday/Thursday: Classes and Data Abastraction

Structure Definitions

"Structures" (AKA C structs) are aggregate data types built using elements of other types. Consider the following structure definition:
struct Time
{
  int hour;       // in the range of 0-23
  int minute;     // in the range of 0-59
  int second;     // in the range of 0-59
};
Structure variables can then be declared as in:
  Time timeObject;
  Time timeArray[10];
  Time *timePtr;
  Time &timeRef = timeObject;
Members of a structure can then be accessed with the dot operator or the arrow operator:
  cout << timeObject.hour;
  cout << timeRef.hour;

  timePtr = &timeObject;
  cout << timePtr->hour;  // Equivalent to (*timePtr).hour
There are some drawbacks to using structures. First, there is no automatic data initialization (the above code will give undefined results). Second, there is no mechanism to prevent the client program from setting invalid data. Third, if the implementation of the structure changes, all the using programs must also change. The drawbacks are avoided by using a class for aggregating data.

Class Definitions

The Time abstract data type can be defined as a class like this:
class Time
{
public:
  Time();                        // Default constructor
  void setTime(int, int, int);   // Mutator
  void printMilitary();          // Print function
  void printStandard();          // Print function

private:
  int hour;
  int minute;
  int second;
}


This page established September 7, 1999; last updated January 7, 2000.