S R T B H P N

Chapter-2 Exercises


Programming exercises: C++ Classes:
  1. Write a class that has a single implemented method, void title(const std::string& msg). The method should format the title, as in Exercises-1:7.
    How many methods does this class have? Remember that the compiler will generate certain constructors, a copy assignment operator, and a destructor. The answer depends on whether you stored the msg string as a member of the class - no need to do that for a title, but you might want to add other functionality to the class later. Should you implement the compiler generated methods?
  2. For the class you created in the first exercise, add a method called add(const std::string& text) that accepts a std::string and appends it to a private std::string member. Also, add a method to return the std::string member by value.
    How should you initialize the std::string member? Can you write the "add" method so that it returns a reference an invoking instance of the class? That will allow you to chain calls, e.g., x.add(": one").add(", two").
  3. Build a class with method bool top(const std::string& fileSpec, size_t n). Attempt to open the file, and if that succeeds, display the first N lines.
    Please handle file opening errors in some meaningful way.
  4. Write code for a WidgetUser class that holds a Widget* ptr to a Widget instance on the native heap. Please provide void, copy construction, move construction, copy assignment, move assignment, and destructor methods for this class.
    You may assume that Widget instances have correct copy, move, and destruction semantics. You don't need to provide any specific functionality for Widgets. Consider using annunciating constructors to show that WidgeUser is properly managing its Widget.
  5. Write code for a class that composes a fundamental type and an STL container (if doesn't really matter which). Show, by careful testing, that the class can correctly allow the compiler to generate its default and copy constructors, assignment operator, and destructor. Now replace the composition with aggregation where the fundamental and STL container types are referenced by pointers to the native heap. Show that incorrect operations occur if you don't provide the copy, assignment, and destruction operations. Now add those operations and show that class operations are valid again. Finally, prevent the compiler from generating those methods using =delete. Note that you will have to provide a destructor (why is that?).
    Doing this exercise carefully is the best way I know of for you to learn how to handle compiler generated methods.