Difference Between Constructor and Destructor

Difference Between Constructor and Destructor

5 mins readComment
Esha
Esha Gupta
Associate Senior Executive
Updated on Mar 27, 2024 18:52 IST

Have you ever wondered about the distinguishing roles of constructors and destructors in programming? Constructors initialize new objects, setting up initial states and allocating resources, while destructors clean up, releasing resources and performing necessary cleanup as objects are destroyed. Let's understand more!

In object-oriented programming (OOP), constructors and destructors are special member functions of a class that handle the initialization and cleanup of objects, respectively. Let's see their differences below.

Top OOPs Interview Questions and Answers (2023)
Top OOPs Interview Questions and Answers (2023)
Object-oriented programming (OOP) is a paradigm that uses objects containing data in programming. It has become a fundamental part of software development. Many companies hire professionals who have a good...read more

Table of Content

Difference Between Constructor and Destructor

Below is a table showcasing the differences between the constructor and destructor.

Feature

Constructor

Destructor

Purpose

Initializes a new instance of a class.

Cleans up an instance before it is destroyed.

Timing of Call

Called when an object is created.

Called when an object is destroyed or goes out of scope.

Functionality

Allocates memory and initializes data members.

Releases resources and performs cleanup tasks.

Overloading

It can be overloaded with different parameters.

It cannot be overloaded; only one destructor per class.

Parameters

It can have parameters (default or parameterized).

No parameters.

Explicit Calling

It can be called explicitly (usually not recommended).

It cannot be explicitly called.

Inheritance

Base class constructor must be called explicitly in the derived class constructor if needed.

Base class destructor is automatically called after the derived class destructor.

Class Vs. Object: What are the Differences?
Class Vs. Object: What are the Differences?
class is a blueprint or template for creating objects in object-oriented programming and bjects are the instances of class. In this article we will expore Class Vs. Object. We will...read more

Difference Between Method Overloading And Method Overriding - Simplified
Difference Between Method Overloading And Method Overriding - Simplified
Programming involves many ideas like polymorphism, inheritance, data abstraction, and handling exceptions. Polymorphism, which includes ideas like method overloading and method overriding, is especially interesting to many people. To understand...read more

Inheritance in Java
Inheritance in Java
Delve into the world of Java inheritance, discovering the "IS A" relationship between classes, superclass and subclass dynamics, and the nuances of method overriding. Understand how Java leverages inheritance for...read more

What is a Constructor?

A constructor is a special type of object-oriented programming (OOP) method that is automatically called when an instance of a class is created. Its primary role is to initialize the new object, setting initial values for its properties and performing any other setup or initialization that's necessary. 

Syntax in C++, Python and Java

C++ Constructor Syntax

class ClassName {
public:
    ClassName() {
        // Default constructor code
    }

    ClassName(Type1 arg1, Type2 arg2) {
        // Parameterized constructor code
    }
};

Python Constructor Syntax

class ClassName:
    def __init__(self, arg1, arg2):
        # Constructor code

Java Constructor Syntax

public class ClassName {
    public ClassName() {
        // Default constructor code
    }

    public ClassName(Type1 arg1, Type2 arg2) {
        // Parameterized constructor code
    }
}

Constructors in C++ and its Types
Constructors in C++ and its Types
Constructors in C++ are the member functions that get invoked when an object of a class is created. There are mainly three types of constructors in C++, Default, Parameterized and...read more

Constructors in Python: Definition, Types, and Rules
Constructors in Python: Definition, Types, and Rules
Constructor in python is a special method that is called when an object is created. The purpose of a python constructor is to assign values to the data members within...read more

Constructors in Java Explained
Constructors in Java Explained
In Java, constructors initialize newly created objects, setting their initial state. They share the same name as the class, lack a return type, and are automatically invoked upon object instantiation.Constructors...read more

What is a Destructor?

A destructor is a special method in object-oriented programming (OOP) that is automatically invoked when an object is destroyed or goes out of scope. Its primary role is to release resources and perform clean-up tasks for the object before it is deallocated.

Syntax in C++, Python and Java

C++ Destructor Syntax

class ClassName {
public:
    ~ClassName() {
        // Destructor code
    }
};

Python Destructor Syntax

class ClassName:
    def __del__(self):
        # Destructor code

Java Destructor Syntax

Java does not have destructors in the same way as C++ or Python due to its automatic garbage collection system. Instead, Java provides a mechanism for cleanup through the finalize method, which isn't the same as a destructor but can serve similar purposes in some cases.

 

Example of Constructor and Destructor

Let us see an example of constructor and destructor in C++ below.

In the code below, we define a simple Resource class that dynamically allocates memory for an array of integers to demonstrate how constructors and destructors are used for resource management.


 
#include <iostream>
#include <cstring> // for std::memset
class Resource {
private:
int* data;
size_t size;
public:
// Constructor
Resource(size_t size) : size(size) {
data = new int[size];
std::memset(data, 0, size * sizeof(int)); // Initialize the array with zeros
std::cout << "Resource of size " << size << " allocated." << std::endl;
}
// Destructor
~Resource() {
delete[] data;
std::cout << "Resource freed." << std::endl;
}
// A utility function to fill the array with a value
void fill(int value) {
for (size_t i = 0; i < size; ++i) {
data[i] = value;
}
}
// A utility function to print the array
void print() const {
for (size_t i = 0; i < size; ++i) {
std::cout << data[i] << ' ';
}
std::cout << std::endl;
}
};
int main() {
size_t size;
int value;
std::cout << "Enter the size of the resource: ";
std::cin >> size;
Resource myResource(size); // Create an instance of Resource with user-defined size
std::cout << "Enter a value to fill the resource: ";
std::cin >> value;
myResource.fill(value); // Fill the array with the user-defined value
myResource.print(); // Print the contents of the array
// When main() returns, myResource will go out of scope and its destructor will be called
return 0;
}
Copy code

Output

Enter the size of the resource: 10
Resource of size 10 allocated.
Enter a value to fill the resource: 1
1 1 1 1 1 1 1 1 1 1 
Resource freed.

Conclusion

Thus, constructors and destructors in object-oriented programming serve complementary yet distinct roles in the lifecycle of an object.

FAQs

What is a constructor, and what is its purpose in object-oriented programming?

A constructor is a special method in object-oriented programming that is called when an object of a class is created. Its purpose is to initialize the object's attributes or perform setup tasks required for the object to function correctly.

How does a destructor differ from a constructor, and what is its role?

A destructor is also a special method, but it is called when an object is about to be destroyed or deallocated, typically at the end of its scope. Its role is to clean up resources or perform any necessary cleanup tasks before the object is removed from memory.

Can a class have multiple constructors?

Yes, a class can have multiple constructors, known as constructor overloading. Overloaded constructors have different parameter lists, allowing objects to be initialized in various ways. This provides flexibility when creating instances of the class.

Is it necessary to define a destructor in every class?

No, it is not necessary to define a destructor in every class. In many cases, the default destructor provided by the programming language is sufficient. Destructors are mainly required when a class manages resources like memory, files, or network connections that need to be released explicitly.

What happens if I don't define a destructor for a class that requires cleanup?

If you don't define a destructor for a class that manages resources, the resources may not be released properly, leading to memory leaks or other resource-related issues. It's essential to define a destructor when necessary to ensure proper cleanup.

About the Author
author-image
Esha Gupta
Associate Senior Executive

Hello, world! I'm Esha Gupta, your go-to Technical Content Developer focusing on Java, Data Structures and Algorithms, and Front End Development. Alongside these specialities, I have a zest for immersing myself in v... Read Full Bio