Difference Between Constructor and Destructor in C++ with Examples
Updated on Jan 30, 2025 | 9 min read | 1.3k views
Share:
For working professionals
For fresh graduates
More
Updated on Jan 30, 2025 | 9 min read | 1.3k views
Share:
Table of Contents
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.
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.’
Get an in-depth understanding of C++ with this detailed C++ Tutorial
#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.
Output:
Car Make: Toyota, Model: Corolla
Learn more about Constructors with this detailed Constructor in C++ with Examples Tutorial
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.
Learn more about Destructors with this detailed Destructor in C++ Tutorial
#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.
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
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++:
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.
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.
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.
Get Free Consultation
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
Top Resources