262 Intermediate C Programming
Notice how the constructor initializes the attributes in the same order as they are de-
clared in the header file. This is a good programming habit. For the sake of clarity, make
things as consistent as possible. This habit prevents accidentally forgetting to initialize an
attribute. Below is the destructor:
#in clude " person .h "1
#in clude < stdlib .h >2
void Pers o n_des truct ( Person * p )3
{4
// p -> name must be freed before p is freed5
free ( p -> name ) ;6
free ( p);7
}8
Note that the destructor releases memory in the reverse order that the construc-
tor allocates memory. This is a general rule. If the destructor free (p) precedes
free (p -> name), then the program will have problems. Why? After free (p), the
object is no longer valid, and free (p -> name) is meaningless and dangerous. Af-
ter calling free (p), the program cannot access the memory that contains the pointer
free (p -> name). There is no guarantee that the address is still accessible. If the destruc-
tor does not call free (p -> name), then the program leaks memory. Thus, as a general
rule, the destructor releases memory in the reverse order that the constructor allocates
memory. Please remember that every malloc must have a corresponding free.
Below is the implementation of the Person print function:
#in clude " person .h "1
#in clude < stdio .h >2
void Person _print ( Person * p )3
{4
printf (" Name : %s. " , p -> name );5
printf (" Date of Birth : %d /% d /% d n" ,6
p -> year , p -> month , p -> date );7
}8
The following is an example of using the constructor and the destructor:
#in clude < stdio .h >1
#in clude < stdlib .h >2
#in clude < string .h >3
#in clude " person .h "4
5
int main ( i n t argc , char * argv [])6
{7
Person * p1 = P erson _const ruct (1989 , 8, 21 , " Amy ") ;8
Person * p2 = P erson _const ruct (1991 , 2, 17 , " Bob ") ;9
Perso n_print ( p1 );10
Perso n_print ( p2 );11
Pers on_des truct ( p1 );12
Pers on_des truct ( p2 );13
return EXIT _SUCCES S ;14
}15
Some students struggle with the difference between objects and pointers to objects. A
pointer stores a memory address. Consider the following example. Please notice how p2 is
created.