Chapter 7: Post Mid-term

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

Mutators and accessors

A class' public functions are commonly classified as either mutators or accessors. A mutator function may modify ("mutate") a class' data members. An accessor function accesses data members but does not modify a class' data members. a mutator for setting the value, and an accessor for getting the value, known as a setter and getter function, respectively, and typically with names starting with set or get. Other mutators and accessors may exist that aren't associated with just one data member, such as the Print() function. Accessor functions usually are defined as const to make clear that data members won't be changed. The keyword const after a member function's name and parameters causes a compiler error if the function modifies a data member. If a const member function calls another member function, that function must also be const.

If any constructor defined, should define default

If a programmer defines any constructor, the compiler does not implicitly define a default constructor, so good practice is for the programmer to also explicitly define a default constructor so that a declaration like MyClass x; remains supported.

Inline member functions on one line

Normally, good style dictates putting a function's statements below the function's name and indenting. But, many programmers make an exception by putting very-short inline member function statements on the same line, for improved readability. This material may use that style at times.

Good practice for .cpp and .h files

Sometimes multiple small related classes are grouped into a single file to avoid a proliferation of files. But for typical classes, good practice is to create a unique .cpp and .h file for each class.

True or False. Good practice is to initialize all variables when declared.

True.

private data members

Variables that member functions can access but class users cannot. Private data members appear after the word "private:" in a class definition.

Class

a construct used to group data and functions to form an object.

private helper functions

commonly created private functions to help public functions carry out tasks

Test Engineers

hired only test other programmers' items. A large percent, like 50% or more, of commercial software development time may go into testing. Testbenches may be complex, with thousands of test cases

A class' public member functions

indicate all operations a class user can perform on the object. The power of classes is that a class user need not know how the class' data and functions are implemented, but need only understand how each public member function behaves.

Regression testing

to retest an item like a class anytime that item is changed; if previously-passed test cases fail, the item has "regressed".

Overloading all equality and relational operators

A common approach is to first overload the == and < operators and then overload other comparison operators using == and <. Overloading != using ==: bool operator!=(const Review& lhs, const Review& rhs) { return !(lhs == rhs); } Overloading >, <=, and >= using <: bool operator>(const Review& lhs, const Review& rhs) { return rhs < lhs; } bool operator<=(const Review& lhs, const Review& rhs) { return !(lhs > rhs); } bool operator>=(const Review& lhs, const Review& rhs) { return !(lhs < rhs); }

inline member function

A member function's definition may appear within the class definition. Two inline member functions exist in the picture. 1) name = restaurantName; located under void SetName(string restaurantName) { 2) rating = userRating; located under void SetRating(int userRating) {

Overloading the equality (==) operator

A programmer can overload the equality operator (==) to allow comparing objects of a programmer-defined class for equality. To overload ==, the programmer creates a function named operator== that returns bool and takes two const reference arguments of the class type for the left-hand-side and right-hand-side operands. Ex: To overload the == operator for a Review class, the programmer defines a function bool operator==(const Review& lhs, const Review& rhs).

NOTE TO SELF

Keep practicing section 7.3 (Defining a class).

this

Within a member function, the implicitly-passed object pointer is accessible via the name this. In particular, a member can be accessed as this->member. The -> is the member access operator for a pointer, similar to the "." operator for non-pointers.

Object

a grouping of data (variables) and operations that can be performed on that data (functions).

Testbench

a program whose job is to thoroughly test another program (or portion) via a series of input/output checks known as test cases.

constructor initializer list

an alternative approach for initializing data members in a constructor, coming after a colon and consisting of a comma-separated list of variableName(initValue) items.

namespace

defines a region (or scope) used to prevent name conflicts. Above, the auditorium seat class code can be put in an auditorium namespace, and airplane seat class code in an airplane namespace. The scope resolution operator :: allows specifying in which namespace to find a name, as in: auditorium::Seat concertSeat; and airplane::Seat flightSeat;.

Unit testing

means to create and run a testbench for a specific item (or "unit") like a function or a class.

only .h files are included

never .cpp files.

name conflict

occurs when two or more items like variables, classes, or functions, have the same name. Ex: One programmer creates a Seat class for auditoriums, and a second programmer creates a Seat class for airplanes. A third programmer creating a reservation system for airline and concert tickets wants to use both Seat classes, but a compiler error occurs due to the name conflict

Constructor

a special class member function called automatically when a variable of that class type is declared, and which can initialize data members. A constructor callable without arguments is a default constructor. See Restaurant in picture. A constructor has the same name as the class. A constructor function has no return type, not even void. Ex: Restaurant::Restaurant() {...} defines a constructor for the Restaurant class. If a class has no programmer-defined constructor, then the compiler implicitly defines a default constructor having no statements.

Overloading the < operator

*Remember*: lhs is left hand side while rhs is right hand side.

RunnerInfo Questions. Fill in the missing blanks.

1) (A) A: private: Data members are private and thus appear after the word "private:". 2) (B) A: RunnerInfo. The class name RunnerInfo (and ::) are prepended to the function name, to associate this function definition with the RunnerInfo class definition. 3) (C) A: RunnerInfo::. The class name RunnerInfo and :: are prepended to the function name, to associate this function definition with the RunnerInfo class definition. 4) (D) A: GetSpeedMph(). A class user can call an object's member function using the "." member access operator, followed by the member function's name (and any required arguments; no arguments are required here). 5) (E) A: runner2.GetSpeedMph(). The class user created two objects: runner1 and runner2. This statement calls a member function on the runner2 object.

Assume a class named Seat.

1) A default constructor declaration in class Seat { ... } is: class Seat { ... void Seat(); } A: False. void shouldn't be there, just: Seat(); 2) A default constructor definition has this form: Seat::Seat() { ... } A: True. The notation may look odd but tells the compiler that this is the constructor. 3) Not defining any constructor is essentially the same as defining a constructor with no statements. A: True. Not finding any programmer-defined constructor, the compiler generates a constructor with no statements. 4) The following calls the default constructor once: Seat mySeat; A: True. The default constructor is called when an object is defined of the class type. 5) The following calls the default constructor once: Seat seat1; Seat seat2; A: False. The default constructor is called for each created Seat object, thus twice. 6) The following calls the default constructor 5 times: vector<Seat> seats(5); A: True. The vector definition creates 5 elements, each being a Seat object. Thus, the Seat constructor is called 5 times.

Considering the picture, answer the following questions.

1) After declaring Restaurant x, a class user can use a statement like x.name = "Sue's Diner". A: False. The name data member is private, accessible by the class' member function, but not by a class user. 2) After declaring a Restaurant object x, a class user can use a statement like myString = x.name. A: False. The name data member is private, and can neither be written nor read by a class user. 3) A class definition should provide comments along with each private data member so that a class user knows how those data members are used. A: False. The class user may never see private data members, and instead need only know of a class' public member functions. (The creator of a class definition may still provide comments for data members, intended for programmers who create/maintain the class definition, not for class users).

Features of a good testbench include:

1) Automatic checks. Ex: Values are compared, as in testData.GetNum1() != 100. 2) Independent test cases. Ex: The test case for GetAverage() assigns new values, vs. relying on earlier values. 3) 100% code coverage: Every line of code is executed. A good testbench would have more test cases than below. 4) Includes not just typical values but also border cases: Unusual or extreme test case values like 0, negative numbers, or large numbers.

7.15.3: Overloading the < operator questions Given the Review class above, complete the definition for the overloaded < operator for the given comparison types. Use const reference parameters, and name the operands lhs and rhs.

1) Review < int bool operator<(const Review& lhs, ____________) { return lhs.GetRating() < rhs; } A: const int& rhs. The operator returns true if the left-hand-side Review operand's rating is less than the right-hand-side int operand. 2) int < Review bool operator<(const int& lhs, const Review& rhs) { return lhs < _______________; } A: rhs.GetRating(). Comparing an int value with a Review object requires a different overloaded < operator than comparing a Review object with an int value. The order of operands matters and must match the order of the operator's parameters. 3) Review < double __________________{ return lhs.GetRating() < rhs; } A: bool operator<(const Review& lhs, const double& rhs). For each desired combination of left-hand-side type and right-hand-side type, a programmer must define an overloaded operator comparing those types.

Given the three constructors below, indicate which will be called for each declaration. class SomeClass { SomeClass(); // A SomeClass(string name); // B SomeClass(string name, int num); // C }

1) SomeClass myObj("Lee"); A, B, C, or Error? A: B. The one string argument matches the one string parameter of B. 2) SomeClass myObj(); A, B, or Error? A: Error. Although calling a regular function with no arguments requires parentheses, for a variable declaration the parentheses must be omitted, else a compiler error occurs 3) SomeClass myObj; A, B, or Error? A: A. The declaration has no argument and constructor A has no parameter, so constructor A is called. A constructor called when no arguments exist is the default constructor. 4) SomeClass myObj("Lee", 5, 0); C or Error? A: Error. The declaration has three arguments, but no constructor has three parameters. The compiler can't find a match so generates an error. 5) vector<SomeClass> myVect(5); A or Error? A: A. myVect is of type vector, so the 5 is used for the vector's constructor. That constructor will create 5 objects of type SomeClass. Lacking arguments, those will use the default SomeClass() constructor.

Which of the following is OK as the entire set of constructors for class YourClass? Assume a declaration like YourClass obj; should be supported.

1) YourClass(); A: OK. The programmer is defining the default constructor. 2) YourClass(string name, int num); A: Error. If a programmer defines any constructor, the programmer should also define a default constructor. Here, the default constructor is missing. Thus, a declaration like YourClass obj; will yield a compiler error. 3) YourClass(string name = "", int num = 0); A: OK. Due to the default parameter values, the constructor supports these declarations: // Initializes with "" and 0 YourClass obj; // Initializes with "Mary" and 0 YourClass obj("Mary"); // Initializes with "Joe" and 1 YourClass obj("Joe", 1); 4) YourClass(); YourClass(string name = "", int num = 0); A: Error. Both constructors can be called with no arguments, so the compiler doesn't know which to call as the default constructor. A compiler error will occur, due to the ambiguity.

7.16.1: Vector functions at(), size(), empty(), and clear() QUESTIONS. Given vector<int> itemList(10); Assume all elements have been assigned 0.

1) itemList().size returns 10. A: False. The syntax is wrong. The () go with the function, size. 2) itemList.size(10) returns 10. A: False. size() does not have a parameter. 3) itemList.size() returns 10. A: True. itemList was declared to have 10 elements. 4) itemList.at(10) returns 0. A: False. Invalid element. The 10 elements are numbered 0 to 9. 5) itemList.empty() removes all elements. A: False. empty() just returns true if the vector size is 0. clear() removes elements. 6) After itemList.clear(), itemList.at(0) is an invalid access. A: True. clear() removes all elements. So there is no element 0.

Given two Review objects named userReview and bestReview, which overloaded operators are called for the following comparisons? Overloading != using ==: bool operator!=(const Review& lhs, const Review& rhs) { return !(lhs == rhs); } Overloading >, <=, and >= using <: bool operator>(const Review& lhs, const Review& rhs) { return rhs < lhs; } bool operator<=(const Review& lhs, const Review& rhs) { return !(lhs > rhs); } bool operator>=(const Review& lhs, const Review& rhs) { return !(lhs < rhs); }

1) userReview != bestReview a) operator== b) operator!= c) operator!= & operator== A: c. operator!= compares the two operands for equality, which calls operator== and then returns the result's negation. 2) userReview > bestReview a) operator< b) operator> c) operator> and operator < A: c. If the left-hand-side operand is greater than the right-hand-side operand, then the right-hand-side operand is less than the left-hand-side operand. So, operator> returns the result of rhs < lhs, which calls operator<. 3) userReview <= bestReview a) operator<= and operator== b) operator<=, operator>, and operator == c) operator<=, operator>, and operator <. A: c. operator<= returns the result of !(lhs > rhs), which calls operator>. operator> then calls operator<.

scope resolution operator

A member function definition that has the class name and two colons (::) preceding the function's name. A member function definition can access private data members.

std namespace

All items in the C++ standard library are part of the std namespace (short for standard). To use classes like string or predefined objects like cout, a programmer can use one of two approaches: Scope resolution operator (::): A programmer can use the scope resolution operator to specify the std namespace before C++ standard library items. Ex: std::cout << "Hello"; or std::string userName; Namespace directive: A programmer can add the statement using namespace std; to direct the compiler to check the std namespace for any names later in the file that aren't otherwise declared. Ex: For string userName;, the compiler will check namespace std for string. For code clarity, most programming guidelines discourage using namespace directives except perhaps for std.

Erroneous unit tests

An erroneous unit test may fail even if the code being tested is correct. A common error is for a programmer to assume that a failing unit test means that the code being tested has a bug. Such an assumption may lead the programmer to spend time trying to "fix" code that is already correct. Good practice is to inspect the code of a failing unit test before making changes to the code being tested.

implicit parameter

An object's member function is called using the syntax object.Function(). The object variable before the function name is known as an implicit parameter of the member function because the compiler converts the call syntax object.Function(...) into a function call with a pointer to the object implicitly passed as a parameter. Ex: Function(object, ...).

Less confusing picture and explanation of "this"

The point of still using "this ->" when the data member and function parameter names differ is to make it clear which one is the private data member.

Constructors with default parameter values

Like any function, a constructor's parameters may be assigned default values. If those default values allow the constructor to be called without arguments, then that constructor can serve as the default constructor. The default values could be in the function definition, but are clearer to class users in the declaration.

Class definition exception to variables being declared before used

Normally, items like variables must be declared before being used, but this rule does not apply within a class definition. Ex: Above, SetRating() accesses rating, even though rating is declared a few lines after. This rule exception allows a class to have the desired form of a public region at the top and a private region at the bottom: A public inline member function can thus access a private data member even though that private data member is declared after the function.

Overloading Constructors

Programmers often want to provide different initialization values when creating a new object. A class creator can overload a constructor by defining multiple constructors differing in parameter types. A variable declaration can have arguments. The constructor with matching parameters will be called.

Two files per class

Programmers typically put all code for a class into two files, separate from other code. - ClassName.h contains the class definition, including data members and member function declarations. - ClassName.cpp contains member function definitions. A file that uses the class, such as a main file or ClassName.cpp, must include ClassName.h. The .h file's contents are sufficient to allow compilation, as long as the corresponding .cpp file is eventually compiled into the program too. The figure shows how all the .cpp files might be listed when compiled into one program. Note that the .h file is not listed in the compilation command, due to being included by the appropriate .cpp files.

Static data members

The keyword static indicates a variable is allocated in memory only once during a program's execution. Static variables reside in the program's static memory region and have a global scope. Thus, static variables can be accessed from anywhere in a program. In a class, a static data member is a data member of the class instead of a data member of each class object. Thus, static data members are independent of any class object, and can be accessed without creating a class object. A static data member is declared inside the class definition, but must also be defined outside the class declaration. Within a class function, a static data member can be accessed just by variable name. A public static data member can be accessed outside the class using the scope resolution operator: ClassName::variableName.

Sorting a vector

The sort() function, defined in the C++ Standard Template Library's (STL) algorithms library, can sort vectors containing objects of programmer-defined classes. To use sort(), a programmer must: 1) Add #include <algorithm> to enable the use of sort(). 2) Overload the < operator for the programmer-defined class. 3) Call the sort() function as sort(myVector.begin(), myVector.end())

vector ADT

The standard template library (STL) defines classes for common Abstract Data Types (ADTs). A vector is an ADT of an ordered, indexable list of items. The vector ADT is implemented as a class (actually a class template that supports different types such as vector<int> or vector<string> For the commonly-used vector member functions below, assume a vector is declared as: vector<T> vectorName(); where T represents the vector's element type, such as: vector<int> teamNums(5);

Table 7.16.1: Vector ADT functions. Notes: size_type is an unsigned integer type. T represents the vector's element type.

at() at(size_type n) Accesses element n. Ex: teamNums.at(3) = 99; // Assigns 99 to element 3 x = teamNums.at(3); // Assigns element 3's value 99 to x size() size_type size() const; Returns vector's size. Ex: if (teamNums.size() > 0) { // Size is 5 so condition is true ... } empty() bool empty() const; Returns true if size is 0. Ex: if (teamNums.empty()) { // Size is 5 so condition is false ... } clear() Removes all elements. Vector size becomes 0. Ex: teamNums.clear(); // Vector now has no elements cout << teamNums.size(); // Prints 0 teamNums.at(3) = 88; // Error; element 3 does not exist push_back() void push_back(const T& x); Copies x to new element at vector's end, increasing size by 1. Parameter is pass by reference to avoid making local copy, but const to make clear not changed. Ex: // Assume vector is empty teamNums.push_back(77); // Vector is: 77 teamNums.push_back(88); // Vector is: 77, 88 cout << teamNums.size(); // Prints 2 erase() iterator erase (iteratorPosition); Removes element from position. Elements from higher positions are shifted back to fill gap. Vector size decrements. Ex: // Assume vector is 77, 33, 88 teamNums.erase(teamNums.begin() + 1); // Now 77, 88 // (Strange position indication explained below) insert() iterator insert(iteratorPosition, const T& x); Copies x to element at position. Items at that position and higher are shifted over to make room. Vector size increments. Ex: // Assume vector is 77, 88 teamNums.insert(teamNums.begin() + 1, 33); // Now 77, 33, 88

static member function

is a class function that is independent of class objects. Static member functions are typically used to access and mutate private static data members from outside the class. Since static methods are independent of class objects, the this parameter is not passed to a static member function. So, a static member function can only access a class' static data members. Figure 7.18.1: Static member function used to access a private static data member.


Ensembles d'études connexes

NU142- Chapter 54: Management of Patients With Kidney Disorders

View Set

BAM410 - ORGANIZATIONAL THEORY AND BEHAVIOR - Unit Exam 4

View Set

Stats Test 3 (Ch. 12-14) Class Notes

View Set

Medical Terminology Chapter 9 Nervous System LO 9.8 Epilepsy

View Set