CS253: Software Development with C++

Spring 2020

IQ 13

CS253 IQ 13

Show Main.IQ13 as a slide show.

Any problems with this code?

class Times {
    const int factor;
  public:
    Times(int f) : factor(f) { }
    int operator()(int n) { return n*factor; }
};

Times f(3);
cout << f(10) << ' ' << f(12); // expect 30 36
30 36
  1. factor is neither public nor private.
  2. factor cann’t be const, since it gets assigned.
  3. operator() must be const.
  4. The ctor should use auto f instead of int f for increased generality.
  5. What fine code!

It would be better if operator() were const, but it’s not necessary.

What will this code produce?

const char *cap = "James T. Kirk";
auto v = find(begin(cap), end(cap), 'T');
cout << v;
c.cc:2: error: no matching function for call to 'begin(const char*&)'

  1. true
  2. T
  3. T. Kirk
  4. some hexadecimal pointer value
  5. none of the above

E: end() is defined for an array, but not for a pointer.

What will this different code produce?

const char cap[] = "James T. Kirk";
auto v = find(begin(cap), end(cap), 'T');
cout << v;
T. Kirk

  1. true
  2. T
  3. T. Kirk
  4. some hexadecimal pointer value
  5. none of the above

C: v is a const char *, a C string—display chars until a null character ('\0').

Finally—no more Kirk!

int a[] = {11,22,33,44,55,66};
auto v = find(a, a+5, 42);
cout << v;
0x7ffded216814
  1. false
  2. nullptr
  3. 66
  4. some hexadecimal pointer value
  5. none of the above

v is an int *, which gets printed in a locale-dependent manner, usually a hexadecimal address.