Destructors

The destructor for a class is called, when





The Danger of Destructors

An object is copied in many situations:

What happens to the dynamically allocated data when one of the copies is "destructed"?
We need duplicate copies of dynamically allocated data!





Copy Constructor

DMC is a class with a dynamically allocated array of int.





Copy Constructor: Syntax





Overloaded Assignment Operator





Assignment: Return Value





Assignment: Memory Leak





Assignment: this Pointer





Assignment: Summary

To complete X = Y, the overloaded assignment operator must:





Member Initializers

Suppose AClass has a DMC data member X and an alternate constructor:

AClass::AClass(const DMC& Y, int n) { X = Y ; stuff = n ; }

This calls the DMC default constructor on X then uses the DMC assignment operator to copy Y into X.

A member initializer calls the DMC copy constructor and is faster:

AClass::AClass(const DMC& Y, int n) : X(Y), stuff(n) { /* do nothing */ }



Remember the BIG 4

The BIG 4 are: default constructor, destructor, copy constructor and assignment operator.