Bruce Eckel's Thinking in C++, 2nd Ed Contents | Prev | Next

Exercises

  1. Write a simple class called Simple with a constructor that prints something to tell you that it’s been called. In main( ) make an object of your class.
  2. Add a destructor to the previous example that prints out a message to tell you that it’s been called.
  3. Modify the previous example so that the class contains an int member. Modify the constructor so that it takes an int argument which it stores in the class member. Both the constructor and destructor should print out the int value as part of their message, so you can see the objects as they are created and destroyed.
  4. Demonstrate that destructors are still called even when goto is used to jump out of a loop.
  5. Write two for loops that print out values from zero to 10. In the first, define the loop counter before the for loop, and in the second define the loop counter in the control expression of the for loop. For the second part of this exercise, modify the identifier in the second for loop so that it as the same name as the loop counter for the first and see what your compiler does.
  6. Modify the Handle.h, Handle.cpp, and UseHandle.cpp files at the end of Chapter 5 to use constructors and destructors.
  7. Use aggregate initialization to create an array of double where you specify the size of the array but do not provide enough elements. Print out this array using sizeof to determine the size of the array. Now create an array of double using aggregate intialization and automatic counting. Print out the array.
  8. Use aggregate initialization to create an array of string objects. Create a Stack to hold these strings and step through your array, pushing each string on your Stack. Finally, pop the strings off your Stack and print each one.
  9. Demonstrate automatic counting and aggregate initialization with an array of objects of the class you created in Exercise 3. Add a member function to that class that prints a message. Calculate the size of the array and move through it, calling your new member function.
  10. Create a class without any constructors, and show that you can create objects with the default constructor. Now create a nondefault constructor (one with an argument) for the class, and try compiling again. Explain what happened.

Contents | Prev | Next


Contact: webmaster@codeguru.com
CodeGuru - the website for developers.
[an error occurred while processing this directive]