Intermediate level · Module 1: Classes, Constructors and Object Lifetime · Lesson 1 of 3
Constructors, Destructors and Lifetime
Follow an object from construction to destruction and use destructors to release resources automatically.
In this lesson you will
- Explain when objects are constructed and destroyed
- Write a destructor and understand RAII
Key concepts
object lifetimedestructor ~T()scopeRAII
The lesson
A local object is constructed when its declaration runs and destroyed automatically at the end of its scope, in reverse order of construction. The destructor, written ~ClassName(), runs at that moment.
This gives C++ its most important idiom, RAII (Resource Acquisition Is Initialisation): acquire a resource such as a file or lock in a constructor and release it in the destructor. The resource is then released on every path out of the scope, including when an exception is thrown.
std::string, std::vector and std::ifstream already follow RAII, which is why you never call close() or free() on them by hand. Your own classes should be built from such members wherever possible.
Step by step
- Write a class that prints a message in its constructor and destructor.
- Create objects in nested scopes and observe the order of messages.
- Throw an exception inside a scope and observe that destructors still run.
- Explain how std::ifstream uses RAII.
Practice activity
Write a Timer class that prints how long a block of code took when the Timer object goes out of scope.
Expected result: Placing a Timer at the start of a block prints the elapsed time automatically at the end of the block.
Check your understanding
-
In what order are local objects destroyed?
Show answer
In reverse order of construction.
-
What does RAII mean in practice?
Show answer
A resource is acquired in a constructor and released in the destructor, so it is always released.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.