Notes, Thursday, October 3


Previous page | Next page


Discussion of Assignment 3

For searching the catalog it helps to realize that searching a catalog results in just another bunch of books, i.e., another Catalog. Hence this kind of function makes sense ...
Catalog Catalog::search (const string& s)
{
    Catalog result;

... inside a loop running through the linked list:

        if ((current->entry.title.find (s) != string::npos) ||
            (current->entry.author.find (s) != string::npos)
           )
           result += current->entry;

... end of loop

    return result;
}
Importantly, for the above to work there needs to be a copy constructor that makes “deep” copies. Also, we need an assignment operator that makes “deep” copies to be able to save and restore results in the main program:
    Catalog catalog;
    Catalog results;
    Catalog savedResults;

    ...

        savedResults = results;
        results = catalog.search (inputString);

        ...

        savedResults = results;
        results = results.search (inputString);

        ...

        results = savedResults;
And of course we need a destructor to avoid memory leaks.

Program the assignment operator to make a real (“deep”) copy of the linked list of catalog nodes. That takes a loop to run through the original that is being copied. The copy constructor then becomes easy because it can use the assignment operator ...

// copy constructor
Catalog::Catalog (const Catalog& cat)
{
    head = NULL;
    *this = cat; // piggy-backing on assignment operator
}
And the destructor is simply using the makeEmpty function we programmed earlier.

So we need the three things you always need when doing dynamic memory allocation (i.e., when you use “new ... ”, whether you are allocating an array or a node pointed to by pointers):

Demos

Thanks to the folks who did demos! We should do that for all the assignments.


Previous page | Next page | Back to top

3:40 PM, Thursday, December 12, 2002