In C++ language, constructors and destructors are special functions that play a crucial role in the lifecycle of an object. The both functions serve to manage resource allocation and deallocation. They are fundamentally different in their purpose and functionality. This article explores the differences between constructors and destructors, and how they are implemented in C++ language.
Introduction to Constructor and Destructor in C++
In C++ language, a constructor is a special member function of a class that is automatically called when an object of the class is created. The primary purpose of a constructor is to initialize the object’s members. Constructors have the same name as the class and do not have a return type. Suppose, we are developers of a video game. In this game, each time a new player registers, we need to assign their initial location, health, acceleration, and certain other quantities to some default value.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
What is a Constructor in C++?
A constructor in C++ is a special member function of a class that is automatically called when an object of that class is created. Its main purpose is to initialize the object. Constructors have the same name as the class and do not have a return type, not even void.
Syntax of Constructor
class heroVired{
public:
heroVired(){
// constructor body
}
}
Characteristics of Constructors in C++
Constructors in C++ are special functions that are automatically called when an object of a class is created. They have several key characteristics:
Same Name as Class: In C++, a constructor has the same name as the class it belongs to. This helps the compiler identify it as a constructor.
No Return Type: Constructors do not have a return type, not even ‘void’. The primary purpose of a constructor is to initialize the object, not to return values.
Automatic Invocation: In C++, Constructors are called automatically when an object is created. There is no need to call them explicitly.
Overloading: Constructors can be overloaded. It means a class can have multiple constructors with different parameters.
Not Inherited: Constructor functions are not inherited, and their addresses cannot be referenced.
Types of Constructors in C++
There are four types of constructors in C++ language:
Default Constructors
Parameterized Constructors
Copy Constructors
Dynamic Constructor
Default Constructor
A default constructor in C++ is a constructor that either has no parameter or all its parameters have default values. Default constructor invoked when an object of the class is created without any arguments. If no constructors are defined in a class, the compiler automatically provides default constructors.
Syntax
<em>//default constructor without any arguments</em>
<em>Person :: Person()</em>
The following program demonstrates the default constructor:
Program
#include <bits/stdc++.h>
using namespace std;
class Person {
public:
int age;
// Default constructor.
Person() {
/* Data member is defined with the help of the
default constructor.*/
age = 23;
}
};
int main() {
// Object of class Employee declared.
Person ob;
// Prints value assigned by default constructor.
cout << ob.age;
return 0;
}
Output
23
Parameterized Constructor
A parameterized constructor in C++ is a constructor that takes or more arguments to initialize an object with specific values. Parameterized constructors provide a way to create objects with initial states based on the arguments passed during object creation.
The following program demonstrates the Parameterized Constructor:
Program
#include <iostream>
using namespace std;
class Person {
public:
int age;
// Parameterized constructor
Person(int x) {
/* Age assigned to value passed as an argument
while object declaration.*/
age = x;
}
};
int main() {
/* Object c1 declared with argument 40, which
gets assigned to age.*/
Person ob1(40);
Person ob2(30);
Person ob3(50);
cout << ob1.age << "n";
cout << ob2.age << "n";
cout << ob3.age << "n";
return 0;
}
Output
40
30
50
Copy Constructor
This is a very special constructor in C++ that creates a new object as a copy of an existing object. This constructor is used to initialize an object with the values of another object of the same class. In simple words, a copy constructor comes into the picture whenever there is a need for an object with the same values for data members as an already existing object.
Syntax
//Copy constructor
Doctor ::Doctor(Doctor &ptr)
The following program demonstrates the copy constructor.
Program
#include<iostream>
using namespace std;
class Doctor {
private:
int salary, experience;
public:
// Parameterized constructor
Doctor(int x1, int y1) {
salary = x1;
experience = y1;
}
// Copy constructor
Doctor(const Doctor &new_employee) {
salary = new_employee.salary;
experience = new_employee.experience;
}
void display() {
cout << "Salary: " << salary << endl;
cout << "Years of experience: " << experience << endl;
}
};
// main function
int main() {
// Parameterized constructor
Doctor ob(34000, 2);
// Copy constructor
Doctor ob2 = ob;
cout << "Object 1 using parameterized constructor : n";
ob2.display();
cout << "Object2 using copy constructor : n";
ob2.display();
return 0;
}
Output
Object 1 using parameterized constructor :
Salary: 34000
Years of experience: 2
Object2 using copy constructor :
Salary: 34000
Years of experience: 2
Dynamic Constructor
A dynamic constructor in C++ is a constructor that allocates memory dynamically(typically using the ‘new’ operator) for one or more data members of a class. This is particularly useful when the size of the data to be stored is not known at compile-time and needs to be determined at runtime.
The following program demonstrates the Dynamic Constructor:
Program
#include <iostream>
using namespace std;
class Person {
int* due_projects;
public:
// Default constructor.
Person() {
// Allocating memory at run time.
due_projects = new int;
*due_projects = 0;
}
// Parameterized constructor.
Person(int x) {
due_projects = new int;
*due_projects = x;
}
void display() {
cout << *due_projects << endl;
}
};
// Main function
int main() {
// Default constructor would be called.
Person ob = Person();
cout << "Due projects for employee1:n";
ob.display();
// Parameterized constructor would be called.
Person ob2 = Person(10);
cout << "Due projects for employee2:n";
ob2.display();
return 0;
}
Output
Due projects for employee1:
0
Due projects for employee2:
10
What is a Destructor in C++?
In C++, a destructor is a special member function of a class. It is invoked automatically when an object of that class is destroyed. Destructor’s primary purpose is to clean up and release any resource that the object may have acquired during its lifetime. This is crucial for managing resources such as dynamic memory, file handles, or network connections, and for preventing resource leaks.
Syntax of Destructor
class HeroVired {
public:
//constructor
HeroVired();
//destructor
~HeroVired();
};
Characteristics of a Destructor in C++
A destructor in C++ is a special member function. It is invoked automatically when an object goes out of scope or is explicitly deleted. Let’s discuss some characteristics of a destructor.
Name and Syntax: A destructor has the same name as the class, preceded by tilde (‘~’). For example, if the class is ‘MyClass’, the destructor will be ‘~MyClass()`.
No Return Type: Unlike other functions, destructors do not have a return type, not even ‘void’ type.
No Parameters: Destructors cannot take parameters and do not return values.
Resource Deallocation: Destructors are commonly used to release resources acquired during the lifetime of the object, such as memory, file handles , or network connections.
Cannot be explicitly called: The destructors are called automatically, you cannot explicitly call a destructor directly, However, You can force a destructor to be called by using ‘delete’ on a dynamically allocated object.
Implementation of Constructors and Destructors in C++
The following program demonstrates the constructors and destructors in C++:
Pogram
#include <iostream>
using namespace std;
class School {
public:
School() {
// Constructor is defined.
cout << "Constructor Invoked for School class" << endl;
}
~School() {
// Destructor is defined.
cout << "Destructor Invoked for School class" << endl;
}
};
class Students {
public:
Students() {
// Constructor is defined.
cout << "Constructor Invoked for Student class" << endl;
}
~Students() {
// Destructor is defined.
cout << "Destructor Invoked for Student class" << endl;
}
};
int main(void) {
// Creating an object of School.
School ob;
// Creating an object of Student.
Students ob2;
return 0;
}
Output
Constructor Invoked for School class
Constructor Invoked for Student class
Destructor Invoked for Student class
Destructor Invoked for School class
Difference Between Constructors and Destructors
Here is a tabular comparison between constructors and destructors in C++ language:
Aspect
Constructor
Destructor
Purpose
Initializes an object when it is created
Clean up and releases resources when an object is destroyed
Name
Same as the class name
Same as the class name preceded by a tilde (‘~’).
Return Type
No return type
No return type
Parameters
This can take parameters (overloaded constructors)
This cannot take parameters
Invocation
This automatically called when an object is created
Automatically called when an object is destroyed
Overloading
This can be overloaded to provide different ways to initialize objects
This cannot be overloaded, only one destructor per class.
Example
‘MyClass(){x=0;};
‘-MyClass() {delete ptr;}’
Conclusion
In this article, we learned that the constructors and destructors are fundamental components of C++ class management, each serving distinct but complementary roles in the object lifecycle. Constructors are special member functions that are invoked when an object is created. They are used to initialize objects, setting up necessary resources and default values. They can be overloaded to provide different initialization options and can take parameters to customize the object’s setup. Constructors facilitate the creation and setup of objects, destructors ensure proper teardown and resource management. Understanding the roles and differences between these functions is crucial for effective memory management and object-oriented programming in C++.
FAQs
What is the primary purpose of a constructor?
The primary purpose of a constructor is to initialize an object’s state when it is created. Constructors set up initial values for the object’s data members and allocate any necessary resources.
What is the main role of a destructor?
The main role of a destructor is to clean up and release resources when an object is destroyed. This includes deallocating memory, closing files, and performing other cleanup tasks to avoid resource leaks.
How do constructors and destructors differ in their syntax?
A constructor has the same name as the class and no return type, not even ‘void’. For example ‘MyClass()’. A destructor also has the same name as the class but is preceded by a tilde (‘~’). For example ‘~MyClass()’.
Can constructors and destructors take parameters?
Constructors can take parameters to allow customized initialization. Destructors. However, I cannot take parameters and do not return values.
When are constructors called?
Constructors are called automatically when an object is instantiated, either on the stack or dynamically on the heap.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.