Difference Between Constructor And Destructor In C++ - C++ Programming Tutorial
C++ Course / C++ vs Other Languages / Difference Between Constructor And Destructor In C++

Difference Between Constructor And Destructor In C++

BLUF: Mastering Difference Between Constructor And Destructor In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Difference Between Constructor And Destructor In C++

C++ is renowned for its efficiency. Learn how Difference Between Constructor And Destructor In C++ enables low-level control and high-performance computing in the tutorial below.

In C++, constructors and destructors play a crucial role in object-oriented programming. Constructors are special member functions responsible for initializing the object's data members, while destructors handle deallocating memory for the object.

In this guide, we will explore the distinctions between constructors and destructors within the C++ programming language. Prior to delving into their variances, it is essential to have a solid understanding of constructors and destructors in C++.

What is a Constructor in C++?

In C++, a constructor is a unique member function that shares the class's name. Its primary purpose is to set the initial values of the class's data members when an object is created. Constructors are invoked automatically upon object instantiation, and they can be defined with or without parameters as needed.

A class can contain multiple constructors, each with different parameter lists, a concept known as constructor overloading. Constructors cannot be inherited or declared as virtual functions. They are typically defined in the public section of a class and do not have a return type in C++.

Syntax:

The format of the constructor in C++ is presented as follows.

Example

class class_name  

    {  

    //Statements  

    class_name ([parameter list])  

    {

    //Statements  

     }  

    };

In this syntax,

  • class_name: It represents the name of the constructor.
  • public: It represents an access specifier.
  • parameter: Parameter list is optional.
  • C++ Constructor Example

Let's consider an example to demonstrate the constructor in C++.

Example

Example

#include <iostream>

using namespace std;

class Employee {

    string Name;

    int ID, Salary;

public:

    // Constructor

    Employee(string emp_name, int emp_id, int emp_sal) {

        Name = emp_name;

        ID = emp_id;

        Salary = emp_sal;

    }

    void display() {

        cout << "Name: " << Name << ", ID: " << ID << ", Salary: " << Salary << endl;

    }

};

int main() {

    // Object creation calls the constructor automatically

    Employee emp1("Jhonson", 101, 45000);

    Employee emp2("Peterson", 201, 80000);

    emp1.display();

    emp2.display();

    return 0;

}

Output:

Output

Name: Jhonson, ID: 101, Salary: 45000

Name: Peterson, ID: 201, Salary: 80000

Explanation:

In this instance, we are demonstrating a class named Employee, which contains a method that initializes the name, ID, and salary for each employee. Subsequently, instances are instantiated for each class. Following this, the display method is employed to showcase the information of every employee.

Characteristics of Constructors

There are several characteristics of constructors in C++. Some main characteristics are as follows:

  • Public Declaration: Constructors are typically defined with the public access specifier so that objects of the class can be generated freely.
  • No Return Type: A constructor does not have any return type, even void.
  • Support for Default attributes: Constructors can accept default parameters, which enables the object initialization to be more flexible.
  • Automatic Invocation: Constructors are invoked automatically during object formation, which helps to avoid the need for explicit calls.
  • Non-Inheritable but Accessible: Derived classes do not inherit constructors, but they can explicitly call the base class constructor to ensure appropriate initialization.
  • What is a Destructor in C++?

In C++, a destructor is a class member function with the class name preceded by the tilde (~) symbol. This function is called automatically when an object of the class is deleted or freed. Typically, destructors are utilized to release various resources like dynamically allocated memory, file operations, and connections associated with the object. Each class can have only a single destructor, and it does not accept any parameters, making it ineligible for overloading.

Syntax:

The syntax of destructors in C++ is given below.

Example

class class_name  

    {  

    ...............;  

    ................;  

    public:  

    class_name();            //constructor  

    ~class_name();           //destructor  

    };

In this code structure, we employ the tilde (~) character to specify the destructor in C++ coding.

C++ Destructor Example

Let's consider a scenario to demonstrate the destructor in C++.

Example

Example

#include <iostream>  

    using namespace std;    //using standard namespace

    class Hello {  

    public:  

      //Constructor  

      Hello () {  

        cout<< "Constructor function is called" <<endl;  

      }  

      //Destructor  

      ~Hello () {  

        cout << "Destructor function is called" <<endl;  

       }  

       //Member function  

       void display() {  

         cout <<"Hello World!" <<endl;  

       }  

    };  

    int main(){    //main function

       //Object created  

       Hello obj;  

       //Member function called  

       obj.display();  

       return 0;  

    }

Output:

Output

Constructor function is called

Hello World!

Destructor function is called

Explanation:

In this instance, a class named Hello is utilized. Upon instantiation of an object from the class, the constructor displays a message, while the destructor shows a message upon the object's destruction. It is important to note that the destructor automatically releases resources when the program concludes.

Characteristics of a Destructor in C++

There are several characteristics of a Destructor in C++. Some of them are as follows:

  • Automatic Memory Cleanup: A destructor releases an object's memory and resources, which ensures that no memory leaks occur when objects are deleted.
  • Cannot be Overloaded: Unlike constructors, a class can only have one destructor. It does not accept parameters or return any value. As a result, destructors cannot handle function overloading.
  • Called in reverse order of construction: Like the stack, destructors follow the LIFO (Last-In-First-Out) procedure. The objects that are generated last are destroyed first. It ensures that resources are properly cleaned up in the reverse order in which they were created.
  • Placement in Class Definition: A destructor can be inserted anywhere inside the class. However, it is usually written near the conclusion of the class definition to improve readability and code organization.
  • Difference between Constructor and Destructor in C++

The subsequent table outlines the diverse variances between the constructor and the destructor within the C++ programming language:

Basis Constructor Destructor
Purpose of use It is used to initialize the data members of an object of the class. It is used to deallocate the memory that the constructor allocated to an object.
Arguments It may or may not contain arguments. It cannot contain the arguments.
Calling It is called automatically when an object of the class is created. It is called automatically whenever the program terminates.
Return type It does not have any return types, not even void. It doesn't have any return type.
Special symbol While declaring a constructor in the C++ programming language, there is no requirement for a special symbol. While declaring a destructor in the C++ programming language, a particular symbol is required, i.e., the tilde (~) symbol.
Utilization We can use more than one constructor in our program. We cannot use more than one destructor in the program.
Inheritance It can be inherited. It cannot be inherited.
Overloading It can be overloaded. It cannot be overloaded.
Execution Order They are executed in successive order. They are executed in the constructor's reverse order; basically, they are the inverse of the constructors.
Types Constructor has four types:Default constructorCopy constructorParameterized constructorDynamic constructor Destructors have no types.
Declaration The following declaration is used for creating a constructor:class classname{............publicclassname ([parameter list]){............}}; The following declaration is used for creating a destructor:class class_name{............;............;public:~xyz();{............};
  • Default constructor
  • Copy constructor
  • Parameterized constructor
  • Dynamic constructor
  • Conclusion

In summary, constructors and destructors are essential member functions in a class that share the class name. While constructors initialize object data members upon creation, destructors handle memory deallocation. Constructors guarantee proper resource allocation, whereas destructors manage cleanup, prevent memory leaks, and ensure efficient resource handling.

1) Can a constructor invoke another constructor in the same class in C++?

Yes, a constructor is alternatively referred to as constructor delegation. This feature enables us to call upon another constructor within the same class in order to recycle the initialization procedure.

2) Can a destructor throw exceptions in C++?

In C++, a destructor cannot throw exceptions as doing so may lead to resource leaks, data loss, and unpredictable program behavior.

3) What happens if a destructor is not defined in a class in C++?

If a destructor is not explicitly defined in C++, the compiler will automatically provide a default destructor to handle resource cleanup.

4) Can constructors and destructors take parameters in C++?

In C++, constructors have the ability to accept parameters for initializing class objects, referred to as parameterized constructors. Conversely, a destructor does not have the capability to accept any parameters for object initialization.

5) Can a constructor be overloaded in C++?

Yes, it is possible to have multiple versions of a constructor in C++. A class can have several constructors within the same class, each sharing the same name but accepting different parameters. This feature enables us to instantiate objects using various initialization methods.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience