⚡0 XP🔥0

Constructors and Destructors

Lesson 5 of 12 ⏱ 6 min read ✎ 2 exercises ❓ 5-question quiz ▶ Runs C++

Default, parameterised and copy constructors, member initializer lists, constructor overloading, destructors and the order in which objects are created and destroyed.

What is a constructor?#

In the previous lesson we created an object and then called setData(). Forgetting that call leaves the object with garbage values. A constructor is a special member function that runs automatically when an object is created, so every object starts in a valid state.

Rules:

  • Same name as the class.
  • No return type (not even void).
  • Can be overloaded (several constructors with different parameters).
▶ Try it YourselfC++
Ctrl + Enter to run
Output
Default constructor
Parameterised constructor
New student: 0
Riya: 88
हिंदी में समझें

Constructor वो function है जो object बनते ही अपने आप चलता है - इसे अलग से call नहीं करना पड़ता। इसका नाम class के नाम जैसा होता है और कोई return type नहीं होता। इससे हर object शुरू से ही सही values के साथ बनता है।

Member initializer lists#

The preferred way to initialise members is the initializer list after a colon:

▶ Try it YourselfC++
Ctrl + Enter to run
Output
P1(3.5, -2)
P0(0, 0)
Tip

Initialise members in the same order they are declared in the class - that is the order C++ actually uses. g++ with -Wall warns if the orders differ.

Default member values and constructor overloading#

Since C++11 you can give members default values right where they are declared:

▶ Try it YourselfC++
Ctrl + Enter to run
Output
Unknown | balance 0 | rate 3.5%
Om | balance 0 | rate 3.5%
Shruti | balance 25000 | rate 3.5%

The copy constructor#

When you create an object from another object, the copy constructor runs. If you do not write one, the compiler generates one that copies every member:

▶ Try it YourselfC++
Ctrl + Enter to run
Output
Copy constructor called
Copy constructor called
Aditya: 445
Aditya (copy): 445
Aditya (copy): 445
Common Mistake

If a class owns raw memory (new in the constructor), the compiler's default copy copies only the pointer, so two objects end up sharing (and later double-freeing) the same memory. Then you must write your own copy constructor, copy assignment and destructor (the "Rule of Three") - or, much better, use std::string / std::vector, which copy correctly by themselves.

Destructors#

A destructor ~ClassName() runs automatically when an object's lifetime ends - when it goes out of scope, or when you delete a dynamically created object. Use it to release resources: close files, free memory, disconnect from a database.

▶ Try it YourselfC++
Ctrl + Enter to run
Output
Login: admin
Login: guest
Inside the block
Logout: guest
Login: temp
Logout: temp
End of main
Logout: admin

Objects on the stack are destroyed in reverse order of creation. This automatic clean-up is called RAII (Resource Acquisition Is Initialization) - acquire a resource in the constructor, release it in the destructor - and it is the heart of safe C++.

हिंदी में समझें

Destructor (~ClassName) object के खत्म होते समय अपने आप चलता है। जो चीज़ constructor ने खोली/ली (file, memory, connection), उसे destructor में बंद/वापस करें। इसे RAII कहते हैं - इससे resource leak होने की संभावना बहुत कम हो जाती है।

new and delete#

new creates an object on the heap and calls its constructor; delete calls the destructor and frees the memory. Arrays use new[] / delete[]:

Student *s = new Student("Neha", 90);
s->show();
delete s;

int *arr = new int[n];
delete[] arr;

Modern C++ prefers smart pointers (std::unique_ptr, std::make_unique) that call delete for you.

Summary#

  • Constructors initialise objects automatically; overload them for different ways of creating objects.
  • Prefer member initializer lists; const and reference members require them.
  • The copy constructor runs when an object is created from another object.
  • Destructors release resources; stack objects are destroyed in reverse order (RAII).

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Book with constructors

Write a class Book with members title, author and price. Add a default constructor (title "Untitled", author "Unknown", price 0) and a parameterised constructor using an initializer list. show() prints Title by Author - Rs price. Output:

Untitled by Unknown - Rs 0
Let Us C by Yashavant Kanetkar - Rs 399
Expected output:
Untitled by Unknown - Rs 0
Let Us C by Yashavant Kanetkar - Rs 399
2

Trace the lifetime

Add a constructor that prints Opening <name> and a destructor that prints Closing <name> to class File. With the given main, the output must be:

Opening report.txt
Opening data.csv
Working...
Closing data.csv
Closing report.txt
Expected output:
Opening report.txt
Opening data.csv
Working...
Closing data.csv
Closing report.txt

Quick Quiz

Q1.

A constructor...

Q2.

When is a destructor called?

Q3.

Point b = a; (a is a Point) calls which constructor?

Q4.

Why prefer a member initializer list (: x(a), y(b))?

Q5.

In which order are local objects destroyed?