Comp 2673, Spring 2002
April 10, lecture notes

Reading: Read Chapter 8 in the Unix book Continue reviewing Chapters 6-8 in Deitel and Deitel Case Study Continued: Here's the declaration (from last lecture) of the class Maze: maze.h Here's an implementation of some of the more interesting functions in this class: maze.cpp Today in class we'll go over all the details of the copy constructor, the assignment operator, and the destructor. If your class has pointers to memory that's been dynamically allocated by the class then your class must include a destructor, a copy constructor, and an overloaded assignment operator. The biggest issue to pay attention to is the allocation of memory (using new) and the de-allocation of memory (using delete). There are some additional details to remember: The copy constructor: - Called automatically whenever you return an object from a function, whenever you pass an object to a function, or define an object and initialize it to be a copy of another object of the same type. - If it doesn't exist, then the compiler defaults to a memberwise copy, which is fine unless you have data members that are pointers to memory that was dynamically allocated by the object - To implement, create a constructor that takes a single parameter that is a reference to the same type as the object. A copy constructor must always take a reference parameter - Data members of a class can be initialized(copied) with member initialization syntax before the body of any constructor - If the object points to dynamically allocated memory, then the copy constructor must allocate space for a copy, then copy the data The destructor - When an object is deleted, its destructor is automatically called. This destructor should de-allocate (release) any memory that was dynamically allocated by the object. It does not need to (and can't) delete itself! The overloaded assignment operator (operator=) - Before making a copy of the parameter, the overloaded assignment operator (operator=) should make sure that the left-hand-object (pointed to by "this") is not the same as the right-hand-object (passed as a parameter). This check looks like if (this != &parameter) - Non-pointer data members are then copied member-wise - if the object points to dynamically allocated memory, then the overloaded assignment operator must allocate space for a copy, then copy the data - An overloaded assignment operator should return a reference to the left-hand object, usually this means return *this