CS210 Lab: Unsorted Lists Prelab Answers

Prelab Answers:

The following are some questions that you can answer prior to the lab.
  1. Find the error in the following code segment:
    	int myarray[5];
    	// Loop to store 5 numbers in the array
    	for (int i=1; i<5; i++) // should be int i=0 	

  2. Write a code segment to dynamically allocate an array (called myarray) of x integers.
    		int x;
    		int *myarray;
    		// Get a value of x 
    		cout << "Please enter a array size: " ;
            	cin >> x;
    		// Dynamically allocate an array
    		myarray= new int[x];

  4. If the constructor for a class called Stash was defined as the following:
    	Stash ( int size, int quantity = 0 );
    which of these two object definitions would be incorrect:
    	Stash A(100);
    	Stash B(100,0);
    This is a trick question; both are correct. Stash's constuctor is making use of a default argument. A default argument is a value given in the declaration that the compiler automatically inserts if you don't provide a value in the function call.

    Therefore, both A and B call the same constructor (and in this case, with the same values). In A's case, the compiler sees that the first argument is an int and that there is no second argument so it automatically inserts the default 0 for the second argument.

    When using default arguments, be aware of two things. First, only trailing arguments may be defaulted. That is, you can't have nondefault arguments after default arguments. Second, once you start using default arguments in a particular function call, all subsequent arguments in that function argument list must be default arguments (following from the first rule).

    Default arguments are only placed in the protype--the declaration of the function (typically in the header file). The definition of the function (typically in the ".cpp" file), does not use this default argument syntax. Therefore, sometimes people will place the commented values of the default arguments in the function definition, for documentation purposes.

    Such as:

    	Stash::Stash ( int size, int quantity /* = 0*/ ){//...

Back to Exercise click here
Back to Unsorted Lists Lab click here

CS Dept Home Page
CS Dept Class Files
CS210 Class Files

Copyright: Department of Computer Science, University of Regina.