1. Home
C++ Tutorial

Explore C++ Tutorials: Exploring the World of C++ Programming

Discover comprehensive C++ tutorials designed for beginners and advanced programmers alike. Enhance your coding skills with step-by-step guides and practical examples.

  • 77 Lessons
  • 15 Hours
right-top-arrow
20

Destructor in C++: Importance and Usage

Updated on 24/09/2024432 Views

As someone with an experience of engaging hands-on with different concepts and ideas in the world of programming and software engineering, I have ample experience of working with many programming languages, including C++. This has enabled me to appreciate the finer nuances of various languages – which make the whole journey all the more satisfying, albeit difficult.

Today, my aim is to tell you about something very important – the destructor in C++ programming language. Understanding destructors is crucial for managing resources efficiently and ensuring robust software design. So without further ado, let’s tackle the first question first - “what is a destructor in C++?”.

What is Destructor in C++?

A destructor in C++ is a unique member function that runs when an object's life finishes. This function is very important for releasing resources the object got while it was alive, like memory allocated dynamically, handles of files, connections to networks or other resources from the system. The destructor has a special name, which you get by adding a tilde (~) before the class's name and it is not allowed to have parameters or give back any value.

The main job of a destructor in C++ is to help with the proper and effective freeing up of resources when an object is not required anymore. Let us examine this role more closely.

  1. Resource management: The destructor simplifies freeing up resources. When an object is no longer in use or removed, the C++ runtime calls upon the destructor by itself to take care of resources that regular methods for handling resources (such as smart pointers) do not manage.
  2. Automatic cleanup: In C++ language, there is no need for you to call cleanup functions by yourself like in some other languages. The destructors of C++ do this job for you without having to tell them explicitly. It makes less chance of forgetting to free resources and guarantees that these resources are let go when an object isn't needed anymore.
  3. Destructors in class hierarchies: In programs with many levels of classes, destructors are very important to make sure that resources used by subclasses get freed correctly. If you have virtual destructors in the main class, it makes sure that when an object from a subclass is pointed at by a reference to the main class, still the right destructor gets called for your subclass object.

So, a cpp destructor is very important for removing everything that an object leaves behind when it's not required anymore. For example, imagine you create a class called FileHandler to open a file when it gets constructed; then the destructor of this class needs to take care of closing the file. This automatic cleaning method stops resources from being wasted, which is a usual cause of errors in coding.

Default Destructor in C++

If you do not create a destructor for a C++ class by yourself, the compiler will make a basic one. This default destructor in C++ is good enough for classes that are simple and do not handle resources that were allocated dynamically or need specific cleaning activities. But, if your class uses complicated actions or resources which must be given back properly, it is necessary for you to create a special destructor.

Here’s how a default destructor in C++ looks like:

class SimpleClass {

public:

~SimpleClass() {

// Compiler-generated or default destructor

}

};

How to Call Destructor C++

In C++, destructors are called automatically when an object goes out of scope or is explicitly deleted when dynamically allocated with new. You typically don't call a destructor explicitly, but there are rare cases in advanced programming where this might be necessary.

SimpleClass* obj = new SimpleClass();

delete obj; // Destructor called here

Virtual Destructor in C++

A virtual destructor is essential in a base class when you work with inheritance and polymorphism. Declaring a destructor as virtual ensures that the destructor of the derived class is called when an object is deleted through a pointer of the base class type. This is crucial for proper resource cleanup in complex object hierarchies.

class Base {

public:

virtual ~Base() {

// Virtual destructor

}

};

class Derived : public Base {

To learn more about polymorphism and virtual destructors, consider enrolling in this comprehensive course on software engineering.

Destructor in C++ Example

Let's look at a practical example of using destructors in C++. Here, I'll demonstrate a Buffer class that allocates dynamic memory.

Example:

Code:

#include <iostream>

using namespace std;

class Buffer {

char* data;

int size;

public:

Buffer(int size): size(size) {

data = new char[size];

cout << "Buffer of size " << size << " created." << endl;

}

~Buffer() {

delete[] data;

cout << "Buffer of size " << size << " destroyed." << endl;

}

};

int main() {

Buffer b(10);

// Destructor called automatically when 'b' goes out of scope

return 0;

}

Output:

Buffer of size 10 created.

Buffer of size 10 destroyed.

Destructor Program in C++

To explain more, we look at bigger examples of destructors in C++. This sample will show how destructors work with different parts like dynamic memory and constructors, and the way they help to make a program stable and run well.

Imagine having a class named UserProfile that takes care of the information in a user's profile. This class will show how to use constructors to set things up and destructors for cleaning up, so you can see how destructors are used when building actual programs.

Here’s a destructor program in C++ illustrating that:

Example:

Code:

#include <iostream>

#include <cstring>

using namespace std;

class UserProfile {

private:

char* username;

int age;

public:

// Constructor to initialize the user profile

UserProfile(const char* name, int userAge) {

age = userAge;

username = new char[strlen(name) + 1];

strcpy(username, name);

cout << "UserProfile created for " << username << ", age " << age << "." << endl;

}

// Destructor to clean up the dynamically allocated memory

~UserProfile() {

cout << "UserProfile for " << username << " is being deleted." << endl;

delete[] username;

}

// A simple method to display the profile information

void displayProfile() {

cout << "Username: " << username << ", Age: " << age << endl;

}

};

int main() {

UserProfile user1("Alice", 28);

user1.displayProfile();

UserProfile user2("Bob", 35);

user2.displayProfile();

// Destructors will be called automatically for user1 and user2

// when they go out of scope at the end of the main function

return 0;

}

Output:

UserProfile created for Alice, age 28.

Username: Alice, Age: 28

UserProfile created for Bob, age 35.

Username: Bob, Age: 35

UserProfile for Alice is being deleted.

UserProfile for Bob is being deleted.

In this program:

  • UserProfile is a class that contains user information such as username and age.
  • The constructor allocates memory for the username and initializes it along with the age.
  • The destructor in the UserProfile class makes sure to delete the username that was created with dynamic allocation, so there's no memory waste.
  • The displayProfile method is used to output the contents of the UserProfile.

Destructors in C++ are called by themselves to clear resources when objects are no longer in use, like when they leave the scope. This situation occurs at the finish of main() function. The automatic clearing is good for stopping usual mistakes like memory leaks and pointers without a target, making C++ programs more stable and dependable.

Characteristics of Destructor in C++

Destructors in C++ are special functions inside a class that have important features for controlling resources when the program runs. Now, let's look at what makes destructors in C++ different. Here are some of the important characteristics of destructor in C++:

  1. No parameters and no return type:
    • Destructors do not have parameters. They are written without using parentheses and any kind of parameters, which shows that they are automatically called without needing to pass in arguments.
    • They give back no value, not even void; this shows that their only purpose is to clean up, and not to do any calculation or processing which would give a result.
  1. Automatic invocation:
    • When an object finishes its life in C++, the system running it calls destructors by itself. This calling without manual input occurs when the object is no longer within scope or someone uses delete to remove it, but this is for objects that were made using new.
    • The automatic control helps to stop resources from being wasted and makes sure that cleaning processes are done in a dependable way.
  1. Non-refundable:
    • A class is limited to only one destructor and the language rules do not permit the creation of more than a single destructor for any class, ensuring resources are released in a stable and expected manner.
  1. Inheritance and polymorphism:
    • When we talk about inheritance, the role of destructors is very important. If you do not mark a destructor in the base class with 'virtual', and you destroy an object using a pointer from the base class, then the derived class's destructor will not execute. This causes resources to leak.
    • A virtual destructor makes sure that when an object is deleted, the right destructor for that specific type of object gets called. This is very important to manage resources well in systems where you have many levels of classes inheriting from each other.
  1. Cannot be overloaded:
    • A class can have only one destructor function which cannot be made into many versions. It always has the same structure and is special for managing resources.
  1. Invoked in reverse Order of construction:
    • For items that have complex structures, such as arrays or objects with fixed or temporary storage time, the system calls their destructors opposite to how it built them. This method of Last In, First Out means that the object made last is destroyed first. This process is very important for keeping the program stable when there are many layers of objects inside each other.
  1. Destructors and exception safety:
    • It is not good for destructors to cause exceptions. If they do while another exception is being handled, the program will stop working. So, it is important that destructors do not allow exceptions to escape and they should be noexcept if possible or make sure to catch any exceptions inside them.

When programmers learn these features, they can make better use of destructors to improve the efficiency and reliability of their C++ programs, while avoiding typical mistakes in managing resources. If you want to increase your knowledge and improve your coding abilities, Upgrad offers detailed courses in software engineering that cover advanced topics in C++.

Concluding Remarks

To manage resources well and avoid memory leaks in C++, it is important to know how destructors work. They help release resources the right way, which improves your code's efficiency and strength. If you want to improve your C++ and get better at programming, Upgrad's software engineering classes are a very good place to begin.

FAQs

1. What is a destructor in C++?

A destructor in C++ is a unique function inside a class that runs when an object's existence finishes, and it helps to tidy up resources the object gathered while it was alive.

2. What is an example of a destructor?

A destructor, like ~Buffer() found in the Buffer class, is for removing memory that has been allocated dynamically to stop leaks of memory.

3. How is a destructor declared?

You declare a destructor by adding a tilde (~) before the class name, so it looks like ~ClassName(), and you cannot give it parameters or say that it returns something.

4. When is a destructor called?

A destructor gets called on its own when an object is no longer in the scope or if someone used new to create it and then removes it.

5. Why are destructors important?

Destructors play a key role in freeing up resources that an object has taken, like memory or file handles, to stop resource leaks and guarantee good management of these resources.

6. Can I define multiple destructors in a class?

Each class is allowed just one destructor, and if there are multiple it's a syntax error in C++.

7. Can a destructor be virtual?

If polymorphism and inheritance are in your code, it is necessary to make a destructor virtual. This will help clean up objects from the derived class correctly when they are reached via pointers of the base class.

8. Can exceptions be thrown from destructors?

It is possible to throw exceptions from destructors, but it's seen as a poor choice because this can cause unpredictable behavior if you do not manage it with caution, particularly when the stack is unwinding for other exceptions.

Rohan Vats

Rohan Vats

Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming eng…Read More

Need Guidance? We're Here to Help!
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...