We’ve talked a lot about using pointers to share information, but mainly as something that causes problems.
In that case, we rely on implementing our own deep copying so that every "container" has distinct copies of all of its components.
class Catalog {
⋮
Catalog ( const Catalog & c );
Catalog & operator = ( const Catalog & c );
~ Catalog ();
⋮
private :
Book * allBooks ; // array of books
int numBooks ;
};
Catalog :: Catalog ( const Catalog & c )
: numBooks ( c . numBooks )
{
allBooks = new Book [ numBooks ];
copy ( c . allBooks , c . allBooks + numBooks , allBoooks );
}
Catalog & Catalog :: operator = ( const Catalog & c )
{
if ( * this != c )
{
delete [] allBooks ;
numBooks = c . numBooks ;
allBooks = new Book [ numBooks ];
copy ( c . allBooks , c . allBooks + numBooks , allBoooks );
}
return * this ;
}
Catalog ::~ Catalog ()
{
delete [] allBooks ;
}
For some data structures, this is OK. If we are using a pointer mainly to give us access to a dynamically allocated array, we can copy the entire array as necessary. In the example shown here, we would want each catalog to get its own distinct array of books. So we would implement a deep copy for the assignment operator and copy constructor, and delete the allBooks pointer in the destructor.