Assignment 2 Solutions This document contains solutions to assignment 2. It is also the Marking Rubric for Assignment 2 used by the TA as a guideline. The TA also uses his own judgment and discretion during marking. Some marks may vary slightly. If you have concerns, please first raise them with the TA using the cmpt-135-help@sfu.ca email address. Scott A. Written Assignment For part A, since there is no code, the 10 marks are all for correctness. If their text/doc/pdf file does not include student name, number, email, then deduct 2 marks (20% of the total for part A). If the submitted doc is hard to read, deduct up to 3 marks for clarity (30%). If their submission is an image file of a handwritten answer, give them zero. One mark each. Avoid half marks, give students full mark if in doubt. Student does not need to provide the full answer provided in the rubric for a full mark, but should include the ideas underlined (although the wording need not be identical). 1. Chapter 10 Classes 10 Marks (a) What is the benefit of encapsulation? Main benefit is reducing system complexity Treat data or object as a black box hides implementation details hides data details Reduces inter-module coupling Increases intra-module cohesion (b) What is the difference between a Struct and a Class A struct is an aggregation of data but defines no methods associated with that data. A Class defines both data and methods associated with managing that data. Both serve to encapsulate and hide complexity. Class members default to private, struct members to public. 1
(c) What is the difference between an Object and a Class? A Class is a blue print for an object. It defines a set of variables, methods, and interfaces but has no state and reserves no memory space for those variables. An Object is an instantiation of a Class and is assigned a new copy of any instance data associated with that class. It has both state and methods that operate on that state. (d) Are members of a class public or private by default? Structs and Classes have both Public and Private sections. Class members are private by default. One must place the keyword public before members to make them visible externally. Struct members are public by default. (e) What are constructors used for? Constructors are special methods called when an object is instantiated in order to initialize the object s data and initial state. (f) What does it mean to overload constructor? Constructors may be overloaded by defining multiple constructors with different parameter signatures within the same class declaration. Methods and functions may be overloaded in the same way by a class defining multiple functions with different signatures. Methods may be overridden when a derived/child class redefines the base/parent constructor with the same signature (g) What is an aggregate object? An aggregate object is an object that contains other objects as instance data. That is, an aggregate object is made up of other objects. An aggregate struct is a data structure that contains other defined data structures. That is, an aggregate struct is made up of other data structures. (h) Describe the difference between a public and private method. A public method has global scope and can be used by any method that has visibility to its class. 2
A private method has only local scope and can only be used within the class that defines it and friends of that class. (i) Describe what an Abstract Data Type (ADT) is and why we use them? An Abstract Data Type (ADT) hides the details about how the data type is implemented, so the user can focus on what it can be used for. An ADT allows the implementation to be changed without impacting users since their interface to the ADT is perserved. ADTs reduce system complexity by hiding details from users. (j) What is Inheritance and what is its key benefit? Inheritance allows derived classes to be created that re-use the existing methods and data of the base class. It's key benefit is software re-use. It allows new services to quickly benefit from existing software features and already tested designs. Re-Use results in more reliable software systems that are produced quicker with less effort. 3
B. Written Assignment Submit in CourSys For part B questions 1-4, since there is no code, the marks are all for correctness. If their text/doc/pdf file does not include student name, number, email, then deduct 20% of the total. If the submitted doc is hard to read, deduct up to 30% for clarity. If their submission is an image file of a handwritten answer, give them zero. 1. Class Definition Questions Multiple Choice 10 Marks Questions with one correct answer only: Score [1] if you choose the correct answer and do not choose another, score [0.5] if you choose one correct answer and one incorrect answer, score [0] if no correct answer is chosen, or more than two are chosen. If the question has 2 correct answers: [1] if you choose both correct, [0.5] if you choose one correct and one incorrect, [0.5] if you choose one correct and do not choose other, [0] if no correct answer chosen or more than two are chosen. Correct Answers will be highlighted in blue. (a) Assume that we are defining a Book class, and one of the instance variables is title. To prevent the possibility that the title of a book object is changed from outside the Book class, unless it is done via the setter method settitle(), the variable title has to be declared as: 1) friend 2) public 3) private 4) void 5) class (b) To allow the title of a book object to be changed from outside the Book class via the setter method settitle(), the method settitle() has to be declared as: 1) friend 2) class 3) private 4) public 5) void (c) To allow the non-member function outputtitle(book book) to access book's private member variable title directly, outputtitle() has to be declared within the Book Class as: 1) friend 2) class 4
3) private 4) public 5) void (d) When passing parameters by value to a C++ method that are BASIC DATA TYPES, the corresponding actual and formal parameters (respectively, the corresponding parameters when calling the method and those declared in the called method): 1) are references to different objects 2) become aliases to the same data in memory 3) are static variables 4) are different variables containing the same value 5) cannot be references to arrays (e) When passing parameters that are ARRAYs to a C++ method, the corresponding actual and formal parameters: 1) are references to different objects 2) become aliases to the same data in memory 3) are static variables 4) are variables containing the same value 5) cannot be references to arrays (f) In order to preserve the encapsulation of an object, we would do the following in the class defining the object: 1) declare the instance variables as private in the class 2) write a Tester class associated to the class defining the object 3) declare the methods of the class defining the object as void 4) include private getter and setter methods in the class 5) define only one constructor method and not more (g) Assume that a method receives an array of strings as a pass-by-value parameter and the method modifies some elements of the array. To be able to see the changes in the array outside the method: 1) The method necessarily has to be defined of type String[] and the modified array needs to be returned from the method 2) The method may be defined to return any type. The changes in the array can be seen outside the method regardless. 3) No changes will be seen because the array was passed-by-value 4) The elements of the array may be changed. While the elements of the array may refer to a different string object, the array will be changed. 5) Because it is an array, the parameter was passed to the method by value, and thus the changes cannot be seen outside the method. (h) A constructor is used in a Class definition to: 1) Define how methods are built 2) Allow object state information to be initialized upon instantiation 3) Return constructed primitive data types back to the invoker 4) Accept parameters used to instantiated the object 5
5) Construct class definitions at compile-time (i) Method Overloading occurs when: 1) More than one class implement the same method 2) A method is invoked too often 3) A method is implemented multiple times in the same class with different signatures 4) A method is used to implement more than one thing 5) A method has the same name and parameters but returns different types (j) Method Overriding occurs when: 1) A method is implemented multiple times in the same class with different signatures 2) A child class provides a method with the same signature as its parent class 3) A child class provides a method with the same signature as an ancestor class in the class hierarchy 4) A Class catches an exception and handles the error condition 5) A local variable shadows another variable with the same name 6
2. Chapter 7 Arrays 5 Marks Rubric for this section: -1.0 if write up is poorly presented and hard to read -1.0 if contains many grammar or spelling mistakes For each question: 0 if the answer is wrong 0.5 if the answer is incomplete 1.0 if the answer is correct and complete (a) What is an Array? An array is a list of elements located contiguously in memory. The entire list can be referenced by its name, and each element in the list can be referenced individually based on its position in the array using an index. (b) What is an array s element type? An array s element type is the type of values that the array can hold. All values in a particular array have the same type, or are at least of compatible types. Thus, we might have an array of integers, or an array of boolean values, or an array of Dog objects, and so on. (c) How is each element in an array referenced? Each element in an array can be referenced by its numeric position, called an index, in the array. In C++, all array indexes begin at zero. Square brackets are used to specify the index. For example, nums[5] refers to the sixth element in the array called nums. (d) How is an entire array passed as a parameter? Passing the array name as a parameter provides a pointer to the entire array. Any changes made to the array elements will be reflected outside of the method. The pointer itself is passed by value, so while the contents of the array can be modified, the method cannot modify the caller's pointer to the array. (e) What is a command-line argument and how are they accessed? Command-line arguments are the parameters specified when the program is invoked from the linux shell. These parameters are passed to main() as argv, which is a pointer to an array of C strings, plus argc which is the length of the array. 7
3. Chapter 10.4 Introduction to Inheritance 5 Marks Rubric for this section: -1.0 if write up is poorly presented and hard to read -1.0 if contains many grammar or spelling mistakes For each question: 0 if the answer is wrong 0.5 if the answer is incomplete 1.0 if the answer is correct and complete (a) Describe the relationship between a parent class and a child class. A child class is derived from a parent class using inheritance. The methods and variables of the parent class automatically become a part of the child class, subject to the rules of the visibility modifiers used to declare them. (b) How does inheritance support software reuse? Because a new class can be derived from an existing class, the characteristics of the parent class can be reused without the error-prone process of copying and modifying code. Any future enhancements or fixes to the parent class are automatically inherited by the child class. (c) Can a child class access the private member variables of its parent? A child cannot access private member variables of its parent. Like other classes, it has no access to private members. (d) Can a child invoke a public member function of its parent? Yes, a child has access to all public member functions. (e) Can a child declare member functions already declared by its parent? Yes, this is known as over-riding. It allows a derived class to override methods defined by the parent. 8
4. Testing 5 Marks Rubric for this question: -1.0 if write up is poorly presented and hard to read -1.0 if contains many grammar or spelling mistakes For each question: 0 if the answer is wrong 0.5 if the answer is incomplete 1.0 if the answer is correct and complete (a) Describe the difference between Black Box and White Box testing. 2 Marks - one of Block Box and one for White Box Testing Description Black Box testing Tests observable functionality of one or more modules with no regard to internal implementation details. White Box testing has internal implementation knowledge about the system under test. It Tests both external and internal interfaces using implementation knowledge to verify correctness of all internal logic paths (b) Describe the goals and scope of the three types of testing called Unit testing, Integration testing, and System testing. 3 Marks - one of each description of the three testing types Unit Testing: Verifies that an individual Class and its methods function correctly given a set of sample inputs and expected outputs Integration Testing: Verifies that several software components, packages, or classes produced by several teams work together as expected. System Testing: Verifies that the product satisfies customer requirements and meets specific quality objectives and it usually includes regression testcases. 9
5. Data Flow Diagrams 5 Marks Rubric for this question: -2 if write up is poorly presented and hard to read -1 Mark for each missing constructor No penalty for lack of comments +1 Bonus if comments are brief but clear 1 Mark for Gambler Class declaration 1 Mark for Die Class declaration 1 Mark for Die Roll method returning bool 1 Mark for Gambler RollTheDice method returning an int 1 Mark for private variables for each class match diagram Class declarations: 10
6. UML Diagrams 5 Marks Create a UML Diagram that describes the classes in the Data Flow Diagram above. Your UML diagram must show the relationship between the two classes, their public member functions, and private member variables. You may draw the UML diagram by hand if desired, then scan into a jpeg file that you include in your assignment write up document. Class relationships in UML Diagrams can get tricky to capture if one gets deep into the subtle nuances of class dependencies versus class associations such as aggregation and composition. For an overview of these concepts and UML in general, the interested student should read: https://en.wikipedia.org/wiki/class_diagram For this course, I have simplified these concepts into just three basic relationships: Dependency (A uses B) Aggregation (A has-a B) Inheritance (A is-a B) In the case of the Gambler and Die classes from question 5, it can be confusing since the Gamble Class uses the Die Class (Dependency), but also has two object instances of the Die class (Aggregation). So which is it? Aggregation is reserved for situations when one class is composed of another object such as when we say a Car has-a Engine. The engine is part of the car. Dependency is used to describe when one object requests services of another object, and is therefore dependent on that object. The Gambler class is dependent on the Die class as shown in the diagram below: 11
Although not correct, a UML diagram that depicts the Aggregation relationship is acceptable for this assignment since the differences were not clearly explained in class. Rubric for this question: -2 if diagram is poorly formatted or hard to read -1 Mark for missing constructors 1 Mark for Gambler and Die Classes 1 Mark for Die Roll method 1 Mark for Gambler RollTheDice method 1 Mark for private variables correct 1 Mark for Dependency marked with Arrow (or Aggregation) 12
C. Programming To be completed by Students Individually You may not use the array or vector classes for this assignment. 1. Passing Arrays to Functions as Parameters 10 Marks Your function called has77 must have the following signature: bool has77(int nums[], int length) { } Rubric: 1 Mark Block Comment at top of file with name, student number, email 1 Mark Function Block Comment describes function, inputs, and outputs 3 Marks Well structured easy to read code (score from 0 to 3) 5 Marks Correctly passes all test cases (-1 per failed testcase) Penalties: 0 Marks if code does not compile -5 Marks if code compiles but does not run Testcases: has77({1, 7, 7},3) true has77({1, 7, 1, 7},4) true has77({1, 7, 1, 1, 7},5) false has77({7, 7, 1, 1, 7},5) true has77({2, 7, 2, 2, 7, 2},6) false has77({2, 7, 2, 2, 7, 7},6) true has77({7, 2, 7, 2, 2, 7},6) true has77({7, 2, 6, 2, 2, 7},6) false has77({7, 7, 7},3) true has77({7, 1, 7},3) true has77({7, 1, 1},3) false has77({1, 2},2) false has77({1, 7},2) false has77({7},1) false 13
2. Modifying Arrays in a Method 10 Marks Your function called withoutten must have the following signature: void withoutten(int nums[], int length) { } Rubric: 1 Mark Block Comment at top of file with name, student number, email 1 Mark Function Block Comment describes function, inputs, and outputs 3 Marks Well structured easy to read code (score from 0 to 3) 5 Marks Correctly passes all test cases (-1 per failed testcase) Penalties: 0 Marks if code does not compile -5 Marks if code compiles but does not run Testcases: withoutten Number of Testcases: 10 withoutten({ 1, 10, 10, 2},4)={ 1, 2, 0, 0} result={ 1, 2, 0, 0} withoutten({10, 2, 10},3)={ 2, 0, 0} result={ 2, 0, 0} withoutten({ 1, 99, 10},3)={ 1, 99, 0} result={ 1, 99, 0} withoutten({10, 13, 10, 14},4)={13, 14, 0, 0} result={13, 14, 0, 0} withoutten({10, 13, 10, 14, 10},5)={13, 14, 0, 0, 0} result={13, 14, 0, 0, 0} withoutten({10, 10, 3},3)={ 3, 0, 0} result={ 3, 0, 0} withoutten({ 1},1)={ 1} result={ 1} withoutten({13, 1},2)={13, 1} result={13, 1} withoutten({10},1)={ 0} result={ 0} withoutten({},0)={} result={} Congrats! All tests passed! 14
3. Two Dimensional Arrays 10 Marks Rubric: 1 Mark Block Comment at top of file with name, student number, email 1 Mark Function Block Comment describes function, inputs, and outputs 3 Marks Well structured easy to read code (score from 0 to 3) 1 Mark Internally double avg[] correctly computed and stored 1 Mark Row number and Avg correctly printed out as specified 1 Mark Internally int randomnum[][] correctly uses indexing [row][col] 1 Mark randomnum[][] correctly printed as [row][column] 1 Mark Numbers under 10 correctly left padded with a space Penalties: -2 Marks if output formatting does not match example test run -2 Marks if any average contains a non-zero in the second decimal place -2 Marks if no averages contain a non-zero in the first decimal place -2 Marks - if random numbers do not change after each test run -5 Marks if code compiles but does not run -10 Marks if code does not compile Example test run: (testcase output should match exactly) Array2d Row 0: 29 3 22 48 25 24 26 56 24 84 Avg=34.10 Row 1: 43 95 53 64 93 30 32 14 41 34 Avg=49.90 Row 2: 11 81 26 69 35 23 94 24 87 3 Avg=45.30 Row 3: 87 39 20 14 81 65 83 18 22 67 Avg=49.60 Row 4: 87 49 79 83 85 15 80 65 26 17 Avg=58.60 15
4. Command Line Parameters 5 Marks Rubric: 1 Mark Well commented File and Function Block Comments 1 Mark Well structured easy to read code (score of 0 or 1) 3 Marks For passing each testcase Penalties: -2 Marks if output does not match example test run formatting exactly -3 Marks if code compiles but does not run -5 Marks if code does not compile Test Cases: Testcase 1: No Command Line Parameters CmdLine There are 0 command line parameters: Testcase 3: Two Command Line Parameters CmdLine Hello World There are 2 command line parameters: "Hello" "World" Testcase 4: 5 Command Line Parameters (example from assignment) CmdLine These are command line parms There are 5 command line parameters: "These" "are" "command" "line" "parms" 16
5. Abstract Data Types and Operator Overloading 20 Marks RationalTest.cpp uses the same formatting from assignment 1, but uses your new overloaded operators to verify that the student's code produces the same results. The output is expected to be identical. In addition, specific test cases will be used to verify that your operators and Rational Class works as specified. Rubric: 2 Marks Well commented File and Function Block Comments 3 Marks Well structured easy to read code (score from 0 or 3) 5 Marks Testcase 1 passes 10 Marks 1 Mark each for test cases 2 to 11 Penalties: - 2 Marks if output does not match Testcase 1 formatting exactly - 1 Mark for each math or comparison operator testcase failed -15 Marks if code compiles but does not run -All Marks if code does not compile Test Cases: Testcase 1: Example Test Run (5 Marks) RationalTest Enter a rational number in the form a/b: 15/3 Enter a rational number in the form c/d: 10/2 a=15 b=3 c=10 d=2 Testing: a/b + c/d = (a * d + b * c) / (b * d) 15/3 + 10/2 = (15 * 2 + 3 * 10)/(3 * 2) = 10/1 Testing: a/b - c/d = (a * d - b * c) / (b * d) 15/3-10/2 = (15 * 2-3 * 10)/(3 * 2) = 0/1 Testing: (a/b) * (c/d) = (a * c) / (b * d) 15/3 * 10/2 = (15 * 10) / (3 * 2) = 25/1 Testing: (a/b) / (c/d) = (a * d) / (c * b) 15/3 / 10/2 = (15 * 2) / (10 * 3) = 1/1 Testing: -(a/b) = (-a/b) -(15/3) = (-15 / 3) = -5/1 Testing: (a/b) < (c/d) means (a * d) < (c * b) 15/3 < 10/2 means (15 * 2) < (10 * 3) means 30/1 < 30/1 Testing: (a/b) == (c/d) means (a * d) == (c * b) 15/3 == 10/2 means (15 * 2) == (10 * 3) means 30/1 == 30/1 17
RationalTest.cpp will be enhanced to test each of the following operators automatically. Each test case is worth 1 mark each. Testcase 2: Overloaded + operator Testcase 3: Overloaded - operator Testcase 4: Overloaded * operator Testcase 5: Overloaded / operator Testcase 6: Overloaded negation - operator Testcase 7: Overloaded == operator Testcase 8: Overloaded > operator Testcase 9: Overloaded < operator Testcase 10: Overloaded >> operator Testcase 11: Overloaded << operator 18
D. Programming for Bonus Marks 1. PostFix Rational Expression Evaluator 25 Marks Rubric: 2 Marks Well commented File and Function Block Comments 3 Marks Well structured easy to read code (score from 0 or 3) 10 Marks Testcase 1 passes 10 Marks 1 Mark each for test cases 2 to 11 Penalties: - 2 Marks if output does not match Testcase 1 formatting exactly - 2 Marks for each math or comparison operator testcase failed - 5 Marks if any operator uses cout or cin in its implementation -10 Marks if code compiles but does not run -All Marks if code does not compile Testcase 1: PostFixRational Postfix Rational expression evaluator --> 1/2 1/4 + = tos = 3/4 --> 5/3 1/2 % = tos = 1/6 --> 5 2 % = tos = 1/1 --> dup + + = tos = 13/6 --> ^2 = tos = 169/36 --> inc = tos = 205/36 --> dec = tos = 169/36 --> 4 ^2 = tos = 16/1 --> 2.5 1 + = tos = 7/2 -->.5 - = tos = 3/1 --> 5 1/2 + = tos = 11/2 --> 2.5 + = tos = 8/1 --> Q Bye! Testcases 2-11: Same testcases as 2-11 for Question C5 19
E. Submission Due date: Friday Mar 4 th 11:59pm Late Submissions: If you submit any component after the deadline, it affects the timestamp for the entire submission. If any component is submitted late, the late penalty will be applied to all components. Late Penalty is 10% per day late, or portion of a day late. Late submissions will be accepted up to two days late with the final cut-off Sunday Mar 6 th 11:59pm. 20