What & How & Why

Chapter.14

Answers for chapter 14


Ex.14.1-14.10

ex.14.1
Exercise 14.1: In what ways does an overloaded operator differ from a built-in operator? In what ways are overloaded operators the same as the built-in operators?
  • The difference:
    • Overloaded versions must, at least contain a class type parameter, or be a class member
    • Neither the order of evaluation nor the properties of the short circuit evaluation for some specified operators will be guaranteed by overloaded versions.
    • Overloaded versions can be called directly.
  • The same:
    • precedence and associativity.
ex.14.2
Exercise 14.2: Write declarations for the overloaded input, output, addition, and compound-assignment operators for Sales_data.

CODE : header source test file

ex.14.3
Exercise 14.3: Both string and vector define an overloaded == that can be used to compare objects of those types. Assuming svec1 and svec2 are vectors that hold strings, identify which version of == is applied in each of the following expressions:

(a) "cobble" == "stone" //comparing two pointers
(b) svec1[0] == svec2[0] //string version
(c) svec1 == svec2 //vector version
(d) "svec1[0] == "stone" //string version

ex.14.4
Exercise 14.4: Explain how to decide whether the following should be class members:

(a) % non-member,  Symmetric operators
(b) %= member, compound-assignment operators
(c) ++ //member, Operators that change the state of their object or that are closely tied to their given type
(d) -> //must be member
(e) << //non-member
(f) && //Shouldn’t Be Overloaded, the operator has order of evaluation and short-cut property
(g) == non-member,  Symmetric operators
(h) ()  //must be member

ex.14.5
Exercise 14.5: In exercise 7.40 from § 7.5.1 (p. 291) you wrote a sketch of one of the following classes. Decide what, if any, overloaded operators your class should provide.

(a) Book 
//arithmatic: +, +=
//equality: ==, !=
//stream: << >>

ex.14.6
Exercise 14.6: Define an output operator for your Sales_data class.

Please see Exercise 14.2

ex.14.7
Exercise 14.7: Define an output operator for you String class you wrote for the exercises in § 13.5 (p. 531).

Please see Exercise 13.44

ex.14.8
Exercise 14.8: Define an output operator for the class you chose in exercise 7.40 from § 7.5.1 (p. 291).

CODE : header source test file

ex.14.9
Exercise 14.9: Define an input operator for your Sales_data class.

CODE : header source test file

ex.14.10
Exercise 14.10: Describe the behavior of the Sales_data input operator if given the following input:

(a) 0-201-99999-9 10 24.95
(b) 10 24.95 0-210-99999-9
The first input yields the correct answer. The second input doesn't.
//output
0-201-99999-9 10 249.5 24.95
10 24 22.8 0.95

Ex.14.11-14.20

ex.14.11
Exercise 14.11: What, if anything, is wrong with the following Sales_data input operator? What would happen if we gave this operator the data in the previous exercise?

istream& operator>>(istream& in, Sales_data& s)
{
    double price;
    in >> s.bookNo >> s.units_sold >> price;
    s.revenue = s.units_sold * price;
    return in;
}
This program failed to validate whether the input was in the proper state. The second input won't be correct based on the given inputs.

ex.14.12
Exercise 14.12: Define an input operator for the class you used in exercise 7.40 from § 7.5.1 (p. 291). Be sure the operator handles input errors.

CODE : header source test file

ex.14.13
Exercise 14.13: Which other arithmetic operators (Table 4.1 (p. 139)), if any, do you think Sales_data ought to support? Define any you think the class should include.

Currently, the Sales_data class has been overloaded +, += operators. In my opinion it is good enough.

ex.14.14
Exercise 14.14: Why do you think it is more efficient to define operator+ to call operator+= rather than the other way around?
  • If we implement + through the +=:
    • The += takes a reference, and returns a reference, thus there is no copy happening.
    • The copy happens when + returns the result. (1 copy)
  • If we implement += through the +:
    • First the + needs to create a local object to store the result. (1 copy)
    • Second, the + have to return the temporary result to += by value (2 copies)

In sum, implementing the + based on the += is more effective.

ex.14.15
Exercise 14.15: Should the class you chose for exercise 7.40 from § 7.5.1 (p. 291) define any of the arithmetic operators? If so, implement them. If not, explain why not.

There should be an + and a += to combine the revenue of two books, as well as an equality operator to check if two books have the same ISBN.

CODE : header source test file

ex.14.16
Exercise 14.16: Define equality and inequality operators for your StrBlob (§ 12.1.1, p. 456), StrBlobPtr (§ 12.1.6, p. 474), StrVec (§ 13.5, p. 526), and String (§ 13.5, p. 531) classes.

StrBlob & StrBlobPtr : header source test file
StrVec: header source test file
String: header source test file

ex.14.17
Exercise 14.17: Should the class you chose for exercise 7.40 from § 7.5.1 (p. 291) define the equality operators? If so, implement them. If not, explain why not.

Please see Exercise 14.15

ex.14.18
Exercise 14.18: Define relational operators for your StrBlob, StrBlobPtr, StrVec, and String classes.

StrBlob & StrBlobPtr : header source test file
StrVec: header source test file
String: header source test file

ex.14.19
Exercise 14.19: Should the class you chose for exercise 7.40 from § 7.5.1 (p. 291) define the relational operators? If so, implement them. If not, explain why not.

CODE : header source test file

ex.14.20
Exercise 14.20: Define the addition and compound-assignment operators for your Sales_data class.

CODE : header source

ex.14.21
Exercise 14.21: Write the Sales_data operators so that + does the actual addition and += calls +. Discuss the disadvantages of this approach compared to the way these operators were defined in § 14.3 (p. 560) and § 14.4 (p. 564).

As we discussed in exercise 14.14 before, using + in order to implement += will spend extra but redundant copies on temporaries and returns. CODE : header source test file

ex.14.22
Exercise 14.22: Define a version of the assignment operator that can assign a string representing an ISBN to a Sales_data.

CODE : header source test file

ex.14.23
Exercise 14.23: Define an initializer_list assignment operator for your version of the StrVec class.

CODE : header source test file

ex.14.24
Exercise 14.24: Decide whether the class you used in exercise 7.40 from § 7.5.1 (p. 291) needs a copy- and move-assignment operator. If so, define those operators.

No. The the synthesized version works well for the Book class.

ex.14.25
Exercise 14.25: Implement any other assignment operators your class should define. Explain which types should be used as operands and why.

No other assignment operator needed for Books class.

ex.14.26
Exercise 14.26: Define subscript operators for your StrVec, String, StrBlob, and StrBlobPtr classes.

StrBlob & StrBlobPtr : header source test file
StrVec: header source test file
String: header source test file

ex.14.27
Exercise 14.27: Add increment and decrement operators to your StrBlobPtr class.

CODE : header source test file

ex.14.28
Exercise 14.28: Define addition and subtraction for StrBlobPtr so that these operators implement pointer arithmetic (§ 3.5.3, p. 119).

CODE : header source test file

ex.14.29
Exercise 14.29: We did not define a const version of the increment and decrement operators. Why not?

Incerment & Decrement changes the state of the object itself, thus they must be non-const function.

ex.14.30
Exercise 14.30: Add dereference and arrow operators to your StrBlobPtr class and to the ConstStrBlobPtr class that you defined in exercise 12.22 from § 12.1.6 (p. 476). Note that the operators in constStrBlobPtr must return const references because the data member in constStrBlobPtr points to a const vector.

CODE : header source test file

Ex.14.31-14.40

ex.14.31
Exercise 14.31: Our StrBlobPtr class does not define the copy constructor, assignment operator, or a destructor. Why is that okay?

Because there is only one data member, weak_ptr, and there is no dynamic allocation involved. The synthesized one will handle it well.

ex.14.32
Exercise 14.32: Define a class that holds a pointer to a StrBlobPtr. Define the overloaded arrow operator for that class.

CODE : Q.1

ex.14.33
Exercise 14.33: How many operands may an overloaded function-call operator take?

256.

C++ Language, Annex B - Implementation quantities: … — Parameters in one function definition [256].
ex.14.34
Exercise 14.34: Define a function-object class to perform an if-then-else operation: The call operator for this class should take three parameters. It should test its first parameter and if that test succeeds, it should return its second parameter; otherwise, it should return its third parameter.

CODE : header test file

ex.14.35
Exercise 14.35: Write a class like PrintString that reads a line of input from an istream and returns a string representing what was read. If the read fails, return the empty string.

CODE : header test file

ex.14.36
Exercise 14.36: Use the class from the previous exercise to read the standard input, storing each line as an element in a vector.

Q.1

ex.14.37
Exercise 14.37: Write a class that tests whether two values are equal. Use that object and the library algorithms to write a program to replace all instances of a given value in a sequence.

CODE : header test file

ex.14.38
Exercise 14.38: Write a class that tests whether the length of a given string matches a given bound. Use that object to write a program to report how many words in an input file are of sizes 1 through 10 inclusive.

CODE : header test file

ex.14.39
Exercise 14.39: Revise the previous program to report the count of words that are sizes 1 through 9 and 10 or more.

CODE : header test file

ex.14.40
Exercise 14.40: Rewrite the biggies function from § 10.3.2 (p. 391) to use function-object classes in place of lambdas.

CODE : header test file

Ex.14.41-14.50

ex.14.41
Exercise 14.41: Why do you suppose the new standard added lambdas? Explain when you would use a lambda and when you would write a class instead.

Lambda is more terse than a function object. However, in some cases, we might be able to benefit from using function objects, as the function may be reused. For instance, finding the biggest number. We know various numbers may be present. In this case, if we use lambdas, we end up with duplicated codes, whereas we could implement another function call overloading with a different number of parameters to handle the case.

As a result, lambda should be used for simple or temporary applications. When the case becomes more complex, consider using a function object.

ex.14.42
Exercise 14.42: Using library function objects and adaptors, define an expression to
  • a) Count the number of values that are greater than 1024
  • b) Find the first string that is not equal to pooh
  • c) Multiply all values by 2

CODE : Q.1

ex.14.43
Exercise 14.43: Using library function objects, determine whether a given int value is divisible by any element in a container of ints.

CODE : Q.1

ex.14.44
Exercise 14.44: Write your own version of a simple desk calculator that can handle binary operations.

CODE : Q.1

ex.14.45
Exercise 14.45: Write conversion operators to convert a Sales_data to string and to double. What values do you think these operators should return?
  • when Sales_data is converted to a string, it should return book_no
  • when Sales_data is converted to a double, it should return avg_price()

CODE : header source test file

ex.14.46
Exercise 14.46: Explain whether defining these Sales_data conversion operators is a good idea and whether they should be explicit.

For Sales_data class, it is not a good idea to overload the conversion operators. Conversion operators should be defined only if there is an obvious single mapping between the class type and the conversion type.

ex.14.47
Exercise 14.47: Explain the difference between these two conversion operators:

struct Integral {
    operator const int(); // conversion operator that convert the integral class type to const int type. The member should be a const member
    operator int() const; // conversion operator that convert the integral class type to int type
};

ex.14.48
Exercise 14.48: Determine whether the class you used in exercise 7.40 from § 7.5.1 (p. 291) should have a conversion to bool. If so, explain why, and explain whether the operator should be explicit. If not, explain why not.

No. In general, there is no obvious mapping between the Book class type and any other conversion type.

ex.14.49
Exercise 14.49: Regardless of whether it is a good idea to do so, define a conversion to bool for the class from the previous exercise.

CODE : header source test file

ex.14.50
Exercise 14.50: Show the possible class-type conversion sequences for the initializations of ex1 and ex2. Explain whether the initializations are legal or not.

struct LongDouble {
    LongDouble(double = 0.0);
    operator double();
    operator float();
};
LongDouble ldObj;
int ex1 = ldObj; 
float ex2 = ldObj;

  • The initialization of ex1 is illegal. In order to initialize ex1, the object ldObj of class-type LongDouble need to be converted to int first; however, both custom conversions in LongDouble class-type are equally good for the conversion, which results in an ambiguous result.
  • The initialization of ex2 is good, the float version has the higher rank of conversion. It will convert LongDouble to float to satisfy the assignment's requirement.

Ex.14.51-14.53

ex.14.51
Exercise 14.51: Show the conversion sequences (if any) needed to call each version of calc and explain why the best viable function is selected.

void calc(int);
void calc(LongDouble);
double dval;
calc(dval); // which calc?
In this case, the LongDouble version will convert built-in type double to the longDouble class-type first. The conversion between an arithmetic type and a class-type has the lowest ranking in the best-match process. By contrast, the int version only requires arithmetic conversion, making it higher ranked. Thus, void calc(int) is the best viable function.

ex.14.52
Exercise 14.52: Which operator+, if any, is selected for each of the addition expressions? List the candidate functions, the viable functions, and the type conversions on the arguments for each viable function:

struct LongDouble {
    // member operator+ for illustration purposes; + is usually a nonmember
    LongDouble operator+(const SmallInt&);
    // other members as in § 14.9.2 (p. 587)
};
LongDouble operator+(LongDouble&, double);
SmallInt si;
LongDouble ld;
ld = si + ld; 
ld = ld + si;

  • ld = si + ld;
    • Candidate: all operator + functions (members, non-members, built-in)
    • Viable: Only built-in version. because SmallInt and LongDouble cannot be converted one to another, none of the versions that take an parameter of type SmallInt or LongDouble can be used for the operation.
    • Best Match:None. SmallInt will be converted to int, LongDouble can be converted to both float and double, Thus both operator+(int, float) and operator+(int, double) are equally good.
  • ld = ld + si
    • Candidate: all operator + functions (members, non-members, built-in)
    • Viable: LongDouble member operator + and bulit-in members
    • Best MatchLongDouble member operator + . The operation is equal to ld.operator+(si).
ex14.53
Exercise 14.53: Given the definition of SmallInt on page 588, determine whether the following addition expression is legal. If so, what addition operator is used? If not, how might you change the code to make it legal?

SmallInt s1;
double d = s1 + 3.14;
The function call is an ambiguous call. s1 + 3.14 can call either non-member operator+(const SmallInt&, const SmallInt&), or built-in operation operator+(int, int), because SmallInt object can be converted into int through the conversion operator, and int can be converted into SmallInt type as well through the conversion constructor.

The call can be rewrote as follows in order to make it legal:
double d = s1 + SmartInt(3.14);