19.12. Exercises: Types and Expressions

  1. Imagine you are required to use a library of classes that have been poorly written and you have no way to improve them. (It could happen!) Example 19.22 includes one such badly written example class and a small program that uses it. The program logic shows some objects being created and passed to a function that receives them as const references (an implicit vow not to change them) and then prints an arithmetic result. Unfortunately, because the class was badly written, something goes wrong along the way.

    Example 19.22. src/const/cast/const.cc

    #include <iostream>
    using namespace std;
    
    class Snafu {
    public:
        Snafu(int x) : mData(x) {}
        void showSum(Snafu & other) const {
            cout << mData + other.mData << endl; 
        }
      
    private:
        int mData;
    };
    
    void foo(const Snafu & myObject1,
             const Snafu & myObject2) {
        // [ . . . ]  
        myObject1.showSum(myObject2);
    }
    
    int main() {
    
        Snafu myObject1(12345);
        Snafu myObject2(54321);
    
        foo(myObject1, myObject2);
    
    }
    
    

    Answer these questions.

    1. What went wrong?

    2. What change to the class would fix it?

    Unfortunately, you can't change the class. Come up with at least two ways to fix the program without changing the class definition. What would be the best of these and why?

  2. Example 19.23 is an incomplete attempt to create a class that counts, for each instantiation, the number of times an object's data are printed. Review the program and make it work properly.

    Example 19.23. src/const/cast/const2.cc

    #include <iostream>
    using namespace std;
    
    class Quux {
    public:
        Quux(int initializer) :
            mData(initializer), printcounter(0) {}
        void print() const;
        void showprintcounter() const {
          cout << printcounter << endl; 
        }
    
    private:
        int mData;
        int printcounter;
    };
    
    void Quux::print() const {
        cout << mData << endl; 
    }
    
    int main() {
        Quux a(45);
        a.print();
        a.print();
        a.print();
        a.showprintcounter();
        const Quux b(246);
        b.print();
        b.print();
        b.showprintcounter();
        return 0;
    }
    
    

[ fromfile: types.xml id: None ]