Book Image

The C++ Workshop

By : Dale Green, Kurt Guntheroth, Shaun Ross Mitchell
Book Image

The C++ Workshop

By: Dale Green, Kurt Guntheroth, Shaun Ross Mitchell

Overview of this book

C++ is the backbone of many games, GUI-based applications, and operating systems. Learning C++ effectively is more than a matter of simply reading through theory, as the real challenge is understanding the fundamentals in depth and being able to use them in the real world. If you're looking to learn C++ programming efficiently, this Workshop is a comprehensive guide that covers all the core features of C++ and how to apply them. It will help you take the next big step toward writing efficient, reliable C++ programs. The C++ Workshop begins by explaining the basic structure of a C++ application, showing you how to write and run your first program to understand data types, operators, variables and the flow of control structures. You'll also see how to make smarter decisions when it comes to using storage space by declaring dynamic variables during program runtime. Moving ahead, you'll use object-oriented programming (OOP) techniques such as inheritance, polymorphism, and class hierarchies to make your code structure organized and efficient. Finally, you'll use the C++ standard library?s built-in functions and templates to speed up different programming tasks. By the end of this C++ book, you will have the knowledge and skills to confidently tackle your own ambitious projects and advance your career as a C++ developer.
Table of Contents (15 chapters)

7. Ownership and Lifetime Of Dynamic Variables

Activity 7: Storing the Words of a Book Using Dynamic Variables

Solution:

  1. Start with the skeleton main() program. It might look like this:
    #include <iostream>
    #include <memory>
    using namespace std;
    int main()
    {
        return 0;
    }
  2. Define the word class:
    class word
    {
        friend class line;
        unique_ptr<char[]> ptr_;
        int letters_;
        int spaces_;
        word* next_;
    public:
        word(char const* srcp, int l, int spaces);
        void to_string(char* dstp);
        int size();
    };// end word

    There is a unique_ptr<> to char array that holds the letters of the word, and a count of letters and spaces. Finally, since the words in a line are going to be a linked list, there is a next pointer.

    The constructor copies in the word string and the...