CS 509, Advanced Programming II

Fall 2001 - Test 6


  1. A colleague of yours is writing a class with a sizeable amount of data, and is careful to avoid making extra copies. In particular, your colleague has defined an overloaded operator operator +() that returns a reference to a class value, rather than a class value itself. Being no dummy, your colleague realized that it would be wrong for operator +() to return a reference to a local class value, and instead defined operator +() as

    T & T::operator + (const T & tval) const { 
      static T sum;
      // compute sum = *this + tval
      return sum;
      }
    

    Because sum is static, it will always be around (as long as the program exists) and its reference will always be defined.

    Assuming operator +() should display all the standard behavior expected of addition, has your colleague implemented a trouble-free version of operator +()? Explain.


    Unfortunately, no. The problem is operator +() may need an arbitrary number of static sum variables to produce correct behavior. Consider the function call

    f(t1 + t2, t3 + t4)
    

    where each of the t variables has type T. operator +() sets sum when computing t1 + t2 and then resets sum when computing t3 + t4. To produce correct behavior in this case, operator +() would need two static variables, but that brings up two related problems. The first is how does operator +() know which static variable to use at each call? The second problem is that I can repeat the argument with a three calls, and, more generally, if operator +() has n static variables, I can repeat the argument with n + 1 calls.


  2. True of false: A synthesized copy constructor always calls the synthesized copy constructors of its component class objects. Explain.


    It's false. A synthesized copy constructor calls which ever copy constructor is defined for its component class objects. If the component classes don't explicitly define a copy constructor, then the compiler will synthesize one and that will be called by the containing class. However, if the component class contains an explicitly defined copy constructor, than that's the copy constructor that will be called by the containing class.


  3. The book claims that any of the three Vec functions begin(), end(), and size() can be implemented in terms of the other two. Demonstrate this is true by implementing each function in terms of the other two.


    This is too easy:

    begin() = end() -  size()
    end() = begin() + size()
    size() = end() - begin()
    


  4. Suppose a non-template class has a template member function:

    class C {
      public:
        template<typename t>
        t memfun(t tval) { ... }
      };
    

    How many copies of the class does the compiler create?


    Just one, although the class may contain an arbitrary number of memfun() member functions.



This page last modified on 30 November 2001.