⧼⧼  Previous Page
⧼  Table of Contents  ⧽
Next Page  ⧽⧽

Constructors and Destructors

Computer Programming C++ / Classes

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.

Hover over a question to show the answer.
  1. Do you need to create a constructor in a class? No. If you don't write one the compiler will generate one for you.
  2. 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.
  3. How many constructors can a class have? As many as you want, as long as they have unique signatures.
  4. What is a constructor used for? To instantiate the object and initialize fields.
  5. What is a destructor? A method that runs when an object is destroyed.
  6. What is a destructor used for? It's usually used for clean up. Possibly deleting objects that it's referencing.
  7. How many destructors can a class have? One or none.
⧼⧼  Previous Page
⧼  Table of Contents  ⧽
Next Page  ⧽⧽
© Ryan Appel