Programming Interviews Exposed: Secrets to Landing Your Next Job, 3rd Edition
by John Mongan, Eric Giguere, Noah Kindler
Construction and Destruction
Objects are instances of classes. Creating an object is called constructing the object. Part of the process involves invoking a constructor method in the class. The constructor initializes the state of the object, which usually involves calling (either explicitly or implicitly) the constructors of its parent classes so that they can initialize their part of the object’s state.
Destroying objects is not as straightforward as constructing them. In C++ a method called the destructor is invoked to clean up an object’s state. Destructors are invoked automatically when an object goes out of scope or when the delete operator is used to destroy a dynamically created object — keeping track of objects is important to avoid leaking memory. In languages such as C# and Java, however, the garbage collector is responsible for finding and destroying unused objects, in which case the time and place (it usually happens on a separate, system-defined thread) of the destruction is out of the application’s control. An optional finalizer method is invoked by the system prior to the object’s destruction to give it the opportunity to clean itself up before its “final” destruction. (In C# and Java it’s possible for objects to “resurrect” themselves from destruction in their finalizers.)
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access