CS 1440 Lab 7
· Understanding what constructors are
· Understanding when constructors are called
· Understanding the categories of other member functions
In the Money class in the previous activity, there was a member function called "Set_dollars_and_cents" that was used to give the data members initial values. What would happen if a programmer forgot to call the Set_dollars_and_cents function before calling Display? What values would the data members have? (If you aren't sure, maybe you should conduct an experiment with the program you wrote for the previous activity.) 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:
Money(); /* THE CONSTRUCTOR! */
void Set_dollars_and_cents(int d, int c);
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
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
my_wallet= Money(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.
Copy your money.C file into money2.C and
1. Create overloaded constructors for the class, so that Money objects can be declared either as we did in the previous activity or with an initial value.
2. Create a member function, Round(), that rounds the Money value to the nearest dollar.
3. Add comments to the member functions in the class definition indicating which category (see the paragraph just before "Followup") each belongs to.
4. Debug this new functionality, that is, test what you did in items 1 and 2, and fix any errors you made.