Constructors are special methods that run automatically when an object is instantiated. They are often used to initialize data-members.
Similar to how constructors run automatically when an object is created, destructors are functions that run when an object is destroyed. This is important because if our object creates another object, it will cause a memory leak when it's destroyed.
Review Questions
The following are examples of questions similar to what you can expect to see on the next exam.
- Do you need to create a constructor in a class? No. If you don't write one the compiler will generate one for you.
-
What are the requirements for a constructor? (What makes it a constructor?)
Must not have a return type (not even void), and
must have exactly the same name as the class. - How many constructors can a class have? As many as you want, as long as they have unique signatures.
- What is a constructor used for? To instantiate the object and initialize fields.
- What is a destructor? A method that runs when an object is destroyed.
- What is a destructor used for? It's usually used for clean up. Possibly deleting objects that it's referencing.
- How many destructors can a class have? One or none.