CS 1440 Lab 7

Cover sheetPrevious ActivityNext Activity


Activity 7-4: Constructors, et.al.

Activity Goals

        Understanding what constructors are

        Understanding when constructors are called

        Understanding the categories of other member functions

Activity Procedure

In the Money class in the previous activity, there was a member function called “Initialize” that was used to give the data members initial values.  What would happen if a programmer forgot to call the Initialize function?  What values would the data members have?  To remedy this potential problem, C++ lets each class have a special function called a constructor.  The constructor is called automatically when the variable, the object, is created.  The purpose of the constructor is give initial values to the data members.  The name of the constructor function is the same as the class name.  So, adding a constructor to our money class would make it look like:

class  Money
{
     public:
          Money();            /* THE CONSTRUCTOR! */
          int Dollars(); 
          int Cents();   
          void Initialize(int d, int c); 
          void Add(Money m); 
          void Display();    

     private:
          int dollars;
          int cents;
};

Notice that the constructor has no return type!  Also, notice that this constructor has no parameters.  This is the constructor that is called automatically when you declare a variable object of this class, like

            Money  my_wallet;

If we’d like to give other values as initial values to construct the object we need to “overload” (remember this!!) the constructor with another one that has parameters.  So add this to the class definition:  Money(int d, int c);  to allow us to create an object like this:

            /* int variables bills and change already given values */
            Money  my_wallet(bills, change);

 

Categories of Member Functions

So we now know about one such category:  constructors.  Another category is accessors (sometimes called observers).  These member functions do not change values of data members but return value(s) of data member(s).  Another category is mutators (sometimes called transformers).  These member functions change the values of data members.

 

Activity Followup

Copy your money.C file into money2.C and

1.      Replace the Initialize member function with the overloaded constructors,

2.      Add comments to the members functions in the class definition indicating which category each belongs to.