Destructors, Copy Constructors & Copy Assignment Operators Adapted from Dr. Mary Eberlein
Non-Default Destructor When do you need it? • Memory is allocated in your constructor: use a destructor to delete it. • Otherwise: memory leaks
Copy Constructor & Copy Assignment Operator • Two ways to copy an object: • copy constructor: create a new object that's a copy of an existing object • copy assignment operator: set an existing object equal to another object • For existing Person object p: • Copy constructor: • Person p 2(p); // create new object p 2 using state of existing object p • Or equivalently: Person p 2 = p; • Copy assignment operator: • Person p 2 =. . . ; • p 2 = p; // p 2 is a Person object, and we want to set its state equal to that of p • If we don't define them in our classes, we get a default destructor, copy constructor and copy assignment operator. • When do we need to define our own? If an object has pointers or some other runtime allocation of a resource (e. g. , opening a file). • default copy constructor and assignment operator will do a shallow copy • default destructor will not deallocate memory allocated for an instance variable
Example class String { private: char* str; int length; public: String(const char* str = NULL); // constructor ~String(); String(const String&); // copy constructor // other member functions. . . };
Shallow Copy • Default assignment operator and copy constructor produce a shallow copy String s 1("hello"); String s 2 = s 1; // default copy constructor invoked s 1 s 2 str length 5 'h' 'e' 'l' 5 'o' '