CS 102 Lecture Notes
Week Three, Wednesday/Thursday: Classes (cont.)
Constructors and destructors are called by the operating
system as necessary, never directly by the program.
Constructors
Always provide a default constructor for a class, and any parameter
constructors that are useful. If you don't have a default constructor,
the values of data members will not be initialized. This puts a burden
on the programmer to remember to set their values later.
A constructor can have default arguments. This provides a programming
convenience, but can lead to ambiguities with some classes that have
several parameter constructors (Direction3D, with both a 2-parameter
and a 3-parameter constructor).
Destructors
You must have a destructor if your class uses any heap memory (uses
the new keyword). Not having a destructor will cause a memory
leak in that case. A destructor should free up heap memory (with the
delete keyword) and perform any other necessary cleanup operations
(such as closing an open file).
This page established September 12, 1999; last updated January 17, 2000.