CS12, Lab 3
Week of April 15 – 19
Topics:
·
Constructors
·
Overloading
(two functions with the same name)
·
Methods
calling other methods.
·
Memberwise
copy
·
More
practice with using classes
·
Default
parameters
You will be
modifying the files from Lab 2.
To do:
·
Copy the
files dice.h and dice.cpp from Lab 2 into a new folder.
·
Add a
constructor with one parameter that allows the user to specify the number of
sides at declaration. When setting the number of sides, the constructor should
use the method setNumSides(int).
·
Add a new
roll function that takes one parameter.
The call roll(x) should return a number between 1 and x, inclusive. In other words, roll(x) rolls a
Dice object with x sides. To
achieve this, the method should first change the number of sides of the object
to x (by calling the appropriate method), then roll the object (by calling
roll()).
·
In your main
program (lab3main.cpp),
1. Create
a Dice object with 10 sides (in one statement).
2. Verify that the number of sides is 10 by
outputting the value retuned from getNumSides().
3. Roll the object 3 times, printing the
results of the rolls.
3. Roll
the object again, this time with 5 sides, using the new roll(int) method
4. Check that the number of sides has changed
by outputting the value retuned from getNumSides().
5. Output the number of rolls that the object
has made (should be 4).
6. Declare a second Dice object using the
default constructor.
7. Output the number of sides and the number
of rolls (should be 6 and 0).
8. Assign to this object the value of the
first object declared.
9. Repeat step 7 (values should be 5 and 4
now).
Experiment:
1. What happens when you compile a program with two constructors, one that has no parameters and another with one parameter with a default value? Use an empty main(). Does your program compile?
2. If
the program does compile, try declaring in main() an object with no
parameters. Does your program
compile now?
3. If
the program compiles and runs, how can you check which constructor gets called
if no argument is specified?