01 / 21

Constructors &
Destructors

Learn how C++ objects are born and destroyed: the special member functions that initialize and clean up every object you create.

C++ Object-Oriented Programming

What Is an Object's Lifecycle?

Every C++ object goes through a predictable lifecycle: it is created, it is used, and it is destroyed. Two special member functions control the bookends of this lifecycle.

Create Constructor Use Member Funcs Destroy Destructor

What Is a Constructor?

A constructor is a special member function that is automatically called when an object of a class is instantiated. It has the same name as the class and no return type: not even void.

class Player { public: // Constructor: same name as the class Player() { health = 100; score = 0; } private: int health; int score; };

What Is a Destructor?

A destructor is a special member function called automatically when an object is destroyed. It has the same name as the class, prefixed with a tilde (\(\sim\)). Like constructors, it has no return type.

class Player { public: Player() { health = 100; } // Destructor: tilde + class name ~Player() { // cleanup code runs here } private: int health; };

Why Do We Need Them?

Initialization
Constructors ensure every object starts in a valid state: no garbage values, no uninitialized pointers.
Encapsulation
Setup logic lives inside the class, keeping the user's code clean and focused.
Resource Safety
Destructors guarantee that dynamic memory, file handles, and network sockets are released: no leaks.

Types of Constructors

Constructors Default No parameters Player() Parameterized Takes arguments Player(int hp) Copy Copies another object Player(const Player&)

Constructor Syntax Rules

1
Same name as the class. The function name must exactly match the class name, including capitalization.
2
No return type. Not void, not int: literally nothing before the name.
3
Can be overloaded. A class can have multiple constructors with different parameter lists.
4
Called automatically. Invoked when an object is declared, new'd, or copy-initialized.
5
Usually public. If made private, external code cannot create objects of that class (used in the Singleton pattern).

Destructor Syntax Rules

1
Tilde + class name. Syntax: ~ClassName().
2
No parameters. A destructor takes zero arguments: it cannot be overloaded.
3
No return type. Just like constructors: no void, no int.
4
Only one per class. You can have many constructors, but exactly one destructor.
5
Called automatically. When a stack object goes out of scope, or delete is called on a heap object.

Constructor vs Destructor

Feature Constructor Destructor
Name \(\text{ClassName}()\) \(\sim\text{ClassName}()\)
Parameters Zero or more None
Overloadable? Yes No
Count per class Multiple Exactly one
Called when Object is created Object is destroyed
Purpose Initialize / allocate Clean up / deallocate

Step-by-Step: Writing a Class

1
Define your class and identify the data members (what state does the object hold?).
2
Write a default constructor that sets safe initial values for every member.
3
Write parameterized constructors if users need to supply initial values at creation time.
4
Write a destructor if your class allocates dynamic memory, opens files, or acquires any resource.
5
Test the lifecycle: create an object, use it, let it go out of scope, and verify cleanup happens.

Example 1: Basic Class

class Box { public: Box() { // Default constructor width = 1.0; height = 1.0; } ~Box() {} // Destructor (empty here) double area() { return width * height; } private: double width, height; }; int main() { Box b; // Constructor called cout << b.area(); // prints 1 } // Destructor called here

Example 2: Parameterized Constructor

class Box { public: Box(double w, double h) { // Parameterized width = w; height = h; } double area() { return width * height; } private: double width, height; }; int main() { Box b(5.0, 3.0); // Passes 5 and 3 cout << b.area(); // prints 15 }

Example 3: Dynamic Memory

class Buffer { public: Buffer(int size) { data = new int[size]; // allocate len = size; } ~Buffer() { delete[] data; // deallocate } private: int* data; int len; }; int main() { Buffer buf(100); // allocates 100 ints } // destructor frees them

Order of Construction & Destruction

Construction Order A (first) B (second) C (third) Destruction Order ~C (first) ~B (second) ~A (third) LIFO: Last In, First Out

Common Mistakes

✕ Adding a return type
Writing void Player() turns it into a regular function, not a constructor. No return type at all.
✕ Forgetting delete
Using new in the constructor but not writing a destructor with delete causes memory leaks.
✕ Overloading destructors
Trying to give a destructor parameters. Destructors take zero arguments and cannot be overloaded.

Summary at a Glance

Concept Details
Constructor syntax \(\text{ClassName}(\text{params})\)
Destructor syntax \(\sim\text{ClassName}()\)
Default constructor No parameters, compiler-generated if you write none
Parameterized Takes arguments for custom initialization
Copy constructor \(\text{ClassName}(\text{const ClassName}\&)\)
Destruction order Reverse of construction (LIFO)
When to write destructor When the class manages dynamic resources

Question 1 of 5

Which of the following is true about a constructor in C++?

Question 2 of 5

What is the correct syntax for a destructor of a class named Engine?

Question 3 of 5

If three local objects A, B, and C are created in that order inside a function, in what order are their destructors called when the function ends?

Question 4 of 5

A class uses new in its constructor to allocate a dynamic array. What happens if you do not write a destructor with the corresponding delete[]?

Question 5 of 5

You define a parameterized constructor Box(double w, double h) but no default constructor. What happens when you write Box b;?