Programming in C++

Exercise Sheet 8
    1. Define a class A with a default constructor and a destructor that merely prints something. Test it by
      1. declaring a local object of type A.
      2. creating a dynamic object of type A (using new) and then destroying it (using delete).

    2. Modify the class so that the destructor prints how many times it has run. (You’ll need to add a field to the class.) Test this version.

    3. Create a class B with a member (field) of type A, give it a noisy constructor and destructor like A has, and try creating and destroying objects of class B.

    4. Modify class B so that the member is a pointer to an A, initialized by B’s constructor (using new) and destroyed by it’s destructor (using delete). Try this class out.

    5. Try assigning objects of class B and then deleting them. Also try initializing new ones by copying.
    6. Add an appropriate copy constructor and assignment operator to B, as discussed in the lecture, and test that.

  1. Consider the following class:
            class Person {  
                    string name;  
                    int age;  
            public:  
                    Person(string n, int a) : name(n), age(a) {}  
     
                    string get_name() const { return name; }  
                    int get_age() const { return age; }  
            };

    What special methods (constructors, destructors, assignment operators) will the compiler automatically generate for this class? Write explicit versions of these special methods that are equivalent to the ones the compiler would generate. Are these what you would want?

  2. In the lecture it was stated several times that initialization differs from assignment. Explain how they differ (or not) for the following:
    1. variables of primitive type (e.g. int).

    2. objects

    3. constants

    4. references

  3. Get the little program strings.cc. It contains the String class discussed in the lecture. The program doesn’t do much – just manipulate some strings and print them.

    Change the representation of strings so that the allocated character array can be longer than the string it currently holds. You will need to

    1. add an extra field for the current length of the array.
    2. modify the constructors to set this appropriately.
    3. modify the assignment operator to reuse the existing character array if the new string will fit, instead of deleting it and allocating a new one.

  4. In C++, one can also call a constructor of a class directly. This creates a temporary object. Explain in detail what is happening in the following statement:
            s1 = String("wheel");

    Add output statements to appropriate places to verify your theory.