Book Image

Learning Object-Oriented Programming

By : Gaston C. Hillar
Book Image

Learning Object-Oriented Programming

By: Gaston C. Hillar

Overview of this book

Table of Contents (16 chapters)
Learning Object-Oriented Programming
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Understanding constructors and destructors


When you ask the programming language to create an instance of a specific class, something happens under the hood. The programming language runtime creates a new instance of the specified type, allocates the necessary memory, and then executes the code specified in the constructor. When the runtime executes the code within the constructor, there is already a live instance of the class. Thus, you have access to the attributes and methods defined in the class. However, as you might have guessed, you must be careful with the code you put within the constructor, because you might end up generating large delays when you create instances of the class.

Tip

Constructors are extremely useful to execute setup code and properly initialize a new instance.

So, for example, before you can call the CalculateArea method, you want the Width and Height attributes for each new Rectangle instance to have a value initialized to 0. Constructors are extremely useful when...