C++ : Constructors and destructors



PART 4



Q19: What is a constructor?  Why would I ever use one?
A: Objects should establish and maintain their own internal coherence.  The
`maintaining' part is done by ensuring self-consistency is restored after any
operation completes (ex: by incrementing the link count after adding a new link
to a linked list).  The part about `establishing coherence' is the job of a
constructor.

Constructors are like `init functions'; they build a valid object.  The
constructor turns a pile of incoherent arbitrary bits into a living object.
Minimally it initializes any internally used fields that are needed, but it may
also allocate resources (memory, files, semaphores, sockets, ...).

A constructor is like a `factory': it builds objects from dust.

`ctor' is a typical abbreviation for constructor.



Q20: What are destructors really for?  Why would I ever use them?
A: Destructors are used to release any resources allocated by the object's
constructor.  Ex: a Lock class might lock a semaphore, and the destructor will
release that semaphore.  The usual `resource' being acquired in a constructor
(and subsequently released in a destructor) is dynamically allocated memory.

`dtor' is a typical abbreviation for destructor