codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
⚡

C++ Programming

42 / 87 topics
38OOP Concepts Overview39Classes and Objects40Class Methods41Constructors & Constructor Overloading42Destructors43Access Modifiers / Specifiers44Encapsulation45Abstraction46Friend Functions and Friend Classes47Operator Overloading
Tutorials/C++ Programming/Destructors
⚡C++ Programming

Destructors

Updated 2026-05-12
30 min read

Destructors

In object-oriented programming, constructors are responsible for initializing objects when they are created. However, just as constructors handle the creation of objects, destructors handle the cleanup process when objects are destroyed. Understanding destructors is crucial for managing resources efficiently and avoiding memory leaks in C++. This tutorial will cover the syntax of destructors, when they are called, virtual destructors, and the RAII (Resource Acquisition Is Initialization) pattern.

Introduction

Destructors are special member functions that are automatically invoked when an object goes out of scope or is explicitly deleted. They are used to release resources such as memory, file handles, or network connections that were acquired during the object's lifetime. Proper use of destructors ensures that your program runs smoothly and efficiently, preventing resource leaks.

Destructor Syntax

A destructor has the same name as its class but is prefixed with a tilde (~). It does not have a return type and cannot take any parameters. Here is the basic syntax:

C++
1class MyClass {
2public:
3 ~MyClass() {
4 // Cleanup code here
5 }
6};

When Destructors Are Called

Destructors are called automatically in the following scenarios:

  1. When an object goes out of scope: If a local object is created within a function, its destructor is called when the function exits.
  2. When an object is explicitly deleted: If an object was dynamically allocated using new, its destructor can be called using delete.
  3. When a program terminates: Destructors for global and static objects are called when the program ends.

Example 1: Destructor Called When Object Goes Out of Scope

C++
1#include <iostream>
2
3class MyClass {
4public:
5 ~MyClass() {
6 std::cout << "Destructor called!" << std::endl;
7 }
8};
9
10void createObject() {
11 MyClass obj; // Local object
12}
13
14int main() {
15 createObject(); // Destructor is called here when obj goes out of scope
16 return 0;
17}
Output

Virtual Destructors

When dealing with polymorphic classes (classes that have virtual functions), it's important to use virtual destructors. This ensures that the destructor of the derived class is called when an object is deleted through a pointer to the base class.

Example 3: Non-Virtual Destructor Issue

C++
1#include <iostream>
2
3class Base {
4public:
5 ~Base() {
6 std::cout << "Base destructor called!" << std::endl;
7 }
8};
9
10class Derived : public Base {
11public:
12 ~Derived() {
13 std::cout << "Derived destructor called!" << std::endl;
14 }
15};
16
17int main() {
18 Base* ptr = new Derived();
19 delete ptr; // Only Base destructor is called
20 return 0;
21}
Output
Base destructor called!

Example 4: Virtual Destructor Solution

C++
1#include <iostream>
2
3class Base {
4public:
5 virtual ~Base() { // Virtual destructor
6 std::cout << "Base destructor called!" << std::endl;
7 }
8};
9
10class Derived : public Base {
11public:
12 ~Derived() override {
13 std::cout << "Derived destructor called!" << std::endl;
14 }
15};
16
17int main() {
18 Base* ptr = new Derived();
19 delete ptr; // Both Base and Derived destructors are called
20 return 0;
21}
Output
Derived destructor called!
Base destructor called!

RAII Pattern

The Resource Acquisition Is Initialization (RAII) pattern is a C++ programming idiom that ensures resources are properly acquired and released. This is achieved by tying resource management to the lifetime of objects using constructors and destructors.

Example 5: RAII with File Handling

C++
1#include <iostream>
2#include <fstream>
3
4class FileHandler {
5public:
6 FileHandler(const std::string& filename) : file(filename, std::ios::out) {
7 if (!file.is_open()) {
8 throw std::runtime_error("Could not open file");
9 }
10 }
11
12 ~FileHandler() {
13 if (file.is_open()) {
14 file.close();
15 std::cout << "File closed." << std::endl;
16 }
17 }
18
19 void write(const std::string& data) {
20 file << data;
21 }
22
23private:
24 std::ofstream file;
25};
26
27int main() {
28 try {
29 FileHandler handler("example.txt");
30 handler.write("Hello, world!");
31 } catch (const std::exception& e) {
32 std::cerr << e.what() << std::endl;
33 }
34 return 0;
35}
Output

In this program, the Resource class manages a dynamically allocated array. The constructor allocates the memory, and the destructor releases it.

Summary

  • Destructor Syntax: A destructor has the same name as its class but is prefixed with a tilde (~). It does not have a return type or parameters.
  • When Destructors Are Called: Destructors are called when an object goes out of scope, is explicitly deleted, or when a program terminates.
  • Virtual Destructors: Use virtual destructors in polymorphic classes to ensure that the destructor of the derived class is called when deleting through a base class pointer.
  • RAII Pattern: The RAII pattern ties resource management to the lifetime of objects using constructors and destructors.

What's Next?

In the next topic, we will explore access modifiers and specifiers in C++. Understanding how to control access to class members is essential for encapsulating data and ensuring that your classes are well-designed. Stay tuned!

Note

Always ensure that your destructors properly release resources to avoid memory leaks.

PreviousConstructors & Constructor OverloadingNext Access Modifiers / Specifiers

Recommended Gear

Constructors & Constructor OverloadingAccess Modifiers / Specifiers