View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Difference Between Constructor and Destructor in C++ with Examples

By Pavan Vadapalli

Updated on Jan 30, 2025 | 9 min read | 1.3k views

Share:

In C++, constructors and destructors play a crucial role in the lifecycle of objects, helping manage initialization and cleanup effectively. Understanding the difference between these two special functions is essential for efficient memory and resource management in C++ programs.

A constructor is responsible for setting up an object when it is created, ensuring that it begins with the proper state. On the other hand, a destructor is invoked when the object is destroyed, helping to release resources and perform necessary cleanup tasks like freeing memory or closing file handles.

Proper use of constructors and destructors can help prevent memory leaks, avoid undefined behavior, and optimize program performance. This blog aims to provide a detailed comparison to highlight the difference between constructor and destructor in C++ language, explaining their purpose, syntax, parameters, and similarities.

Build the future with code! Explore our diverse Software Engineering courses and kickstart your journey to becoming a tech expert.

Start Exploring Now!

What Is a Constructor?

A constructor in C++ is a special member function that is automatically invoked when an object of a class is created. Its primary purpose is to initialize the object's data members and allocate resources required for its operation. Constructors ensure that an object starts its life in a valid state, ready to be used. Unlike regular functions, constructors have the same name as the class they belong to and do not have a return type, not even ‘void.’

Characteristics of a Constructor:

  • Same Name as the Class: The constructor must have the exact same name as the class to which it belongs.
  • Automatically Invoked: The constructor is called automatically when an object of the class is instantiated, without needing explicit calls.
  • Can Be Overloaded: A class can have multiple constructors with different parameter lists (called constructor overloading), allowing for different ways of initializing objects.

Get an in-depth understanding of C++ with this detailed C++ Tutorial

Example of a Constructor in C++:

#include <iostream>
using namespace std;

class Car {
public:
    string make;
    string model;

    // Constructor
    Car(string m, string mo) {
        make = m;
        model = mo;
    }

    void displayInfo() {
        cout << "Car Make: " << make << ", Model: " << model << endl;
    }
};

int main() {
    Car myCar("Toyota", "Corolla");  // Constructor called here
    myCar.displayInfo();
    return 0;
}

In this example, we define a Car class with two data members: make and model.

  • The constructor Car(string m, string mo) is used to initialize these members when a Car object is created.
  • In the main function, when the object myCar is created with the values "Toyota" and "Corolla", the constructor is automatically called, setting the make and model values of myCar.
  • The displayInfo() method then prints out the car's make and model.

Output:

Car Make: Toyota, Model: Corolla

Learn more about Constructors with this detailed Constructor in C++ with Examples Tutorial

What Is a Destructor?

A destructor in C++ is a special member function that is called automatically when an object is destroyed. Its primary purpose is to clean up resources that the object may have acquired during its lifetime, such as memory or file handles. While a constructor initializes an object, a destructor ensures that everything is properly cleaned up when the object is no longer needed.

Characteristics of a Destructor:

  • Same Name as the Class with a Preceding ~ Symbol: A destructor has the same name as the class but with a ~ (tilde) symbol before it.
  • Automatically Invoked: The destructor is automatically called when an object goes out of scope or is explicitly deleted using delete.
  • Cannot Be Overloaded: Unlike constructors, destructors cannot be overloaded. A class can only have one destructor.

Learn more about Destructors with this detailed Destructor in C++ Tutorial

Example of a Destructor in C++:

#include <iostream>
using namespace std;

class Car {
public:
    string make;
    string model;

    // Constructor
    Car(string m, string mo) {
        make = m;
        model = mo;
        cout << "Car created: " << make << " " << model << endl;
    }

    // Destructor
    ~Car() {
        cout << "Car destroyed: " << make << " " << model << endl;
    }

    void displayInfo() {
        cout << "Car Make: " << make << ", Model: " << model << endl;
    }
};

int main() {
    Car myCar("Toyota", "Corolla");  // Constructor called
    myCar.displayInfo();
    // Destructor will be called automatically when myCar goes out of scope
    return 0;
}

In this example, the Car class has a constructor and a destructor.

  • The constructor initializes the car’s make and model, and prints a message when the car is created.
  • The destructor is called automatically when the object goes out of scope (at the end of main). It prints a message saying the car is destroyed.

So, when the program runs:

1. The constructor prints:

Car created: Toyota Corolla

2. When the object goes out of scope, the destructor is automatically called and prints:

Car destroyed: Toyota Corolla

Also Read: Top 7 Most Powerful Features of C++ You Should Know About

Differences Between Constructor and Destructor in C++

Constructors and destructors are fundamental concepts in C++ that manage an object’s lifecycle effectively. While constructors initialize an object when it is created, destructors handle cleanup tasks when the object is destroyed. This ensures efficient use of resources and prevents memory leaks. The table below provides a detailed comparison:

Aspect

Constructor

Destructor

Purpose Used to initialize an object and set its initial state by allocating resources or assigning values to variables. Used to release resources such as memory, file handles, or connections, ensuring proper cleanup before the object is destroyed.
Invocation Automatically called when an object is created, either explicitly or implicitly. Automatically called when an object goes out of scope, is explicitly deleted, or the program ends.
Syntax Has the same name as the class without any return type. Has the same name as the class but is preceded by a ~ symbol.
Overloading Can be overloaded to define multiple constructors with different sets of parameters for flexible initialization. Cannot be overloaded; a class can have only one destructor.
Return Type Does not have a return type, not even void, as it is not called like a normal function. Does not have a return type, not even void, as it is implicitly called by the compiler.
Parameters Can take parameters to allow for custom initialization (e.g., parameterized constructors). Cannot take parameters; it does not support arguments.
Execution Order in Derived Classes Executes in the order from the base class to the derived class to ensure proper initialization hierarchy. Executes in reverse order, from the derived class to the base class, to ensure proper cleanup hierarchy.
Frequency of Invocation Invoked only once per object during its lifetime, at the time of creation. Invoked only once per object, just before it is deallocated or goes out of scope.
Memory Management Allocates and initializes resources like memory, objects, or files required by the object. Releases allocated resources, closes file handles, and performs other cleanup operations.
Explicit Call Can be explicitly invoked using initialization syntax or constructor delegation. Cannot be explicitly invoked; it is called automatically by the compiler or during a delete operation.
Support for Inheritance Ensures initialization of base class members and then derived class members in a specific order. Ensures cleanup of derived class members first and then base class members in reverse order.
Default Availability A default constructor is automatically provided by the compiler if no user-defined constructor exists. A default destructor is automatically provided by the compiler if no user-defined destructor exists.

Step into the future of analytics and AI! Join our free Data Science course and learn the fundamentals of this high-demand field.

Start Learning Now!Similarities Between Constructor and Destructor in C++

While constructors and destructors serve opposite purposes, they share several important characteristics that define their role in managing an object’s lifecycle in C++:

  1. Same Name as the Class
    • Both the constructor and destructor have the same name as the class. The only difference is that the destructor is preceded by a ~ symbol.
  2. Automatically Invoked by the Compiler
    • The constructor is automatically called when an object is created, and the destructor is automatically called when the object is destroyed. This eliminates the need for manual function calls.
  3. No Return Type
    • Neither constructors nor destructors have a return type, not even void. This ensures that they cannot return any value when invoked.
  4. Defined by the User or Compiler
    • Both constructors and destructors can be explicitly defined by the user. If not defined, the compiler automatically provides a default constructor and destructor.
  5. Single Invocation per Object
    • Both the constructor and destructor are invoked only once during the lifetime of an object: the constructor at the time of creation and the destructor at the time of destruction.

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months
View Program

Job-Linked Program

Bootcamp36 Weeks
View Program

Conclusion : 

Constructors and destructors play a crucial role in C++ programming by managing the lifecycle of an object. While constructors ensure that objects are properly initialized with the required resources, destructors handle the cleanup, preventing memory leaks and ensuring efficient resource management.

Understanding the difference between constructors and destructors in C++ improves your understanding of object-oriented programming and also helps you write more efficient and effective code. Learning these concepts is an important step toward strengthening your C++ programming skills and building applications that handle resources seamlessly.

How Can upGrad Help?

Learning C++ is a vital step in mastering programming, as it serves as the backbone of many advanced applications, including game development, system software, and performance-critical applications. With its versatility and efficiency, C++ opens doors to a wide range of career opportunities in various industries.

upGrad offers industry-relevant software development courses to help you learn programming and build a strong foundation. Through expertly crafted tutorials, interactive learning resources, and personalized guidance, upGrad ensures that even complex C++ concepts are easy to grasp and apply.

Similar Reads:

Level Up for FREE: Explore Top Tutorials Now!

Python Tutorial | SQL Tutorial | Excel Tutorial | Data Structure Tutorial | Data Analytics Tutorial | Statistics Tutorial | Machine Learning Tutorial | Deep Learning Tutorial | DBMS Tutorial | Artificial Intelligence Tutorial

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

Frequently Asked Questions (FAQs)

1. Can a constructor call another constructor in the same class?

2. What happens if a destructor is not defined in a class?

3. Can constructors and destructors be private in C++?

4. How are constructors and destructors different from normal member functions?

5. Can a destructor throw exceptions in C++?

6. Do constructors and destructors support virtual functions in C++?

7. What is the role of copy constructors in C++?

8. Can a constructor be called more than once for the same object?

9. How does the compiler decide when to call a destructor?

10. Can constructors and destructors be inherited in derived classes?

11. What is the significance of the explicit keyword in constructors?

Pavan Vadapalli

899 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

View Program
upGrad KnowledgeHut

upGrad KnowledgeHut

Angular Training

Hone Skills with Live Projects

Certification

13+ Hrs Instructor-Led Sessions

View Program
upGrad

upGrad KnowledgeHut

Full Stack Development Bootcamp - Essential

Job-Linked Program

Bootcamp

36 Weeks

View Program