🧩 C++ programming tutorial for beginners · Class 11 · Lesson 7 of 18 · Free
Constructors and Destructors in C++ – Object Start-up and Clean-up
⏱ About 35 minutes · ▶ run real C++ here — nothing to install · no sign-in
In this lesson you will
- Write default, parameterized and copy constructors and know when each runs
- Use a member initializer list, including for const members
- Predict when destructors run and use them to release resources (RAII)
A school lab hands out a key when a class enters and takes it back when the class leaves. If someone forgets to return the key, the next class is locked out. C++ objects work the same way: a constructor sets things up when an object is born, and a destructor cleans up automatically when it dies.
What is a constructor in C++ and what types are there?
A constructor runs by itself when an object is created. It has the class's name and no return type, not even void. You met one in Lesson 2.
A class can have several constructors with different parameters, just like overloaded functions (Lesson 4). A default constructor takes no arguments. A parameterized constructor takes some.
You can also give a member a default value where you declare it, like int maxMarks = 100;. Constructors that don't set it keep that value.
Try it: add a third constructor that takes only a name, and create an exam with it.
Default exam: Unit Test /25 Custom exam: Final Exam /100
💡 Write Exam weekly; with no brackets. Exam weekly(); does not make an object (see the mistakes below).
Why use a member initializer list in a C++ constructor?
The list after the colon sets members as they are created. Assigning in the body happens later: the member is first created, then changed.
For most members both ways give the same result. But const members and reference members MUST be set in the list, because they cannot be assigned later.
Members are always set in the order they are declared in the class, not the order you write in the list. Keep both orders the same to avoid surprises.
Try it: move rollNo(r) into the body as rollNo = r; and run. The compiler refuses, because rollNo is const.
Tara (roll 5) won 10 points Vikram (roll 9) won 5 points Red House total: 15
What is a destructor in C++ and when is it called?
A destructor runs by itself when an object is destroyed. Its name is ~ plus the class name, like ~LabKey(). It has no parameters and no return type.
A local object is destroyed when its block ends, at the closing brace }. Objects are destroyed in the reverse order of creation: last made, first gone.
static int inUse is one variable shared by all LabKey objects, not one per object. Here it counts the keys handed out right now.
Try it: create a third key inside the inner block and watch the order of the messages.
Key for Physics Lab given (1 in use) Key for Chemistry Lab given (2 in use) Key for Computer Lab given (3 in use) -- inner block ends -- Key for Computer Lab returned (2 in use) Key for Chemistry Lab returned (1 in use) -- main ends -- Key for Physics Lab returned (0 in use)
What is a copy constructor in C++?
A copy constructor makes a new object from an existing one of the same class. Its parameter is a const reference: Ticket(const Ticket& other).
It runs when you write Ticket b = a;, and when you pass an object to a function by value. C++ writes one for you that copies every member.
Write your own only when a plain member-by-member copy is wrong. Here each copy of a ticket must get a new serial number.
Try it: change show(Ticket t) to show(const Ticket& t) and run. One copy fewer is made.
(copy made: serial 1002) (copy made: serial 1003) Pune-Mumbai #1003 a is #1001, b is #1002
How do destructors free memory in C++ (RAII)?
new[] takes memory from the heap. You must give it back with delete[], or the program leaks memory. Forgetting is easy.
RAII (Resource Acquisition Is Initialization) fixes this: the constructor takes the resource and the destructor gives it back. When the object dies, clean-up happens without you asking.
Copying such an object would make two objects share one block and both delete it. So we forbid copies with = delete. The compiler then stops any copy.
Try it: write MarksList copy = list; in main and run. The compiler blocks it. vector (Lesson 5) does all of this for you, which is why you should usually use it.
Got memory for 4 marks Sum: 235 Gave back memory for 4 marks
💡 This idea is called the rule of three: if a class needs its own destructor, it usually needs its own copy constructor and copy assignment too (or must delete them).
🤔 Predict the output
Think like C++: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
#include <iostream>
using namespace std;
class A {
public:
A() { cout << "+A "; }
~A() { cout << "-A "; }
};
class B {
public:
B() { cout << "+B "; }
~B() { cout << "-B "; }
};
int main() {
A a;
B b;
return 0;
}
Question 2. What does this print?
#include <iostream>
using namespace std;
class Box {
int id;
public:
Box(int i) : id(i) { cout << "+" << id << " "; }
~Box() { cout << "-" << id << " "; }
};
int main() {
for (int i = 0; i < 2; i++) {
Box b(i);
}
cout << "\n";
return 0;
}
Question 3. What does this print?
#include <iostream>
using namespace std;
class Book {
public:
Book() {}
Book(const Book&) { cout << "copy "; }
};
void readByValue(Book b) {}
void readByRef(const Book& b) {}
int main() {
Book x;
readByValue(x);
readByRef(x);
Book y = x;
cout << "\n";
return 0;
}
🧩 Your challenge
Make a school gate register. Class Visitor takes a name in its constructor and prints "IN: <name>"; its destructor prints "OUT: <name>". A static int inside counts visitors in the school. Print the count after each change, like this: IN: Mr. Joshi (1 inside) IN: Parent of Anu (2 inside) OUT: Parent of Anu (1 inside) IN: Plumber (2 inside) OUT: Plumber (1 inside) OUT: Mr. Joshi (0 inside)
IN: Mr. Joshi (1 inside) IN: Parent of Anu (2 inside) OUT: Parent of Anu (1 inside) IN: Plumber (2 inside) OUT: Plumber (1 inside) OUT: Mr. Joshi (0 inside)
⚠️ Common mistakes (and how to fix them)
❌ Wrong
#include <iostream>
using namespace std;
class Student {
int marks;
public:
void Student() { marks = 0; }
};
int main() {
Student s;
cout << "Made\n";
return 0;
}
Line 7: error: constructor cannot have a return type
✅ Right
#include <iostream>
using namespace std;
class Student {
int marks;
public:
Student() : marks(0) {}
int getMarks() const { return marks; }
};
int main() {
Student s;
cout << "Made with marks " << s.getMarks() << "\n";
return 0;
}
A constructor has no return type, not even void. With void in front, the compiler rejects it.
❌ Wrong
#include <iostream>
using namespace std;
class Counter {
int n = 0;
public:
void tick() { n++; }
int get() const { return n; }
};
int main() {
Counter c();
c.tick();
cout << c.get() << "\n";
return 0;
}
Line 13: error: base of member reference is a function; perhaps you meant to call it with no arguments?
✅ Right
#include <iostream>
using namespace std;
class Counter {
int n = 0;
public:
void tick() { n++; }
int get() const { return n; }
};
int main() {
Counter c;
c.tick();
cout << c.get() << "\n";
return 0;
}
Counter c(); declares a FUNCTION named c that returns a Counter, not an object. Write Counter c; or Counter c{};.
❌ Wrong
#include <iostream>
using namespace std;
class Account {
const int number;
public:
Account(int n) { number = n; }
int get() const { return number; }
};
int main() {
Account a(4021);
cout << a.get() << "\n";
return 0;
}
Line 7: error: constructor for 'Account' must explicitly initialize the const member 'number'
✅ Right
#include <iostream>
using namespace std;
class Account {
const int number;
public:
Account(int n) : number(n) {}
int get() const { return number; }
};
int main() {
Account a(4021);
cout << a.get() << "\n";
return 0;
}
A const member cannot be assigned in the constructor's body. Set it in the member initializer list instead.
📌 Remember
- A constructor sets up an object; it has the class name and no return type.
- Use the member initializer list; const and reference members need it.
- A destructor (~Name) runs when the object dies, in reverse order of creation.
- The copy constructor runs on Type b = a; and when passing by value.
- RAII: take a resource in the constructor, release it in the destructor.
Finished the quiz and the challenge?
Questions students ask
Can a constructor be private in C++?
Yes. Then outside code cannot create objects directly, only the class's own functions can. This is used in patterns such as the singleton, covered in Lesson 16.
Can a destructor take parameters or be overloaded?
No. A class has exactly one destructor, with no parameters and no return type. C++ calls it for you, so there is nothing to choose between.
What happens if I don't write a constructor in C++?
The compiler writes a default constructor for you. It creates each member, but plain types like int are left with unknown values unless you give them default values in the class.
Does C++ have garbage collection?
No. Memory and other resources are released by destructors at known times, using RAII. Smart pointers (Lesson 14) and containers like vector do this for you.