11
OctConstructors and Destructors in C ++
Constructors and Destructors in C ++: An Overview
After seeing the basics of OOP concepts in C++, let us now move a step forward. In this C++ tutorial, we will look at an important OOP construct, constructors, and destructors in C++. This topic will now repeat in every OOPs tutorial in C++ like inheritance in C++, polymorphism in C++, etc. Therefore it's very important to get hold of this.For more knowledge and understanding, consider our C++ Certification Course.
What is a Constructor in C++?
A constructor in C++ is a special member function invoked automatically when an object of a class is created. It is generally used to initialize the data members of the new object. They are also used to run a default code when an object is created. The constructor in C++ has the same name as the class or structure and does not have a return value.
Syntax of a Constructor prototype
<class-name> (list-of-parameters);
A constructor in C++ can be defined in two ways:
- inside the class
Syntax
<class-name> (list-of-parameters) { // constructor definition }
Example
class ScholarHat { //class public: //access specifier ScholarHat() { //constructor // code } };
- outside the class using the scope resolution operator
: :
Syntax
<class-name>: : <class-name>(list-of-parameters){ // constructor definition }
Example
ScholarHat: : ScholarHat() { //outside the class constructor // code }
Remember: The access specifier
of a constructor is always public
.
Read More - Advanced C++ Interview Interview Questions and Answers
Types of Constructors in C++
There are three types of constructors in C++:
- Default Constructor in C++
- Parameterized Constructor in C++
- Copy Constructor in C++
- Default Constructor in C++
It is a constructor in C++ with no parameters.
Example of C++ Default Constructor
#include <iostream>
using namespace std;
class Student {
public:
Student() {
cout << "Default Constructor Invoked" << endl;
}
};
int main() {
Student s1; // Creating an object of Student class
Student s2;
return 0;
}
The above C++ code in C++ Online Compiler has a default constructor named Student()
. When the objects s1
and s2
of the Student
class is created, the constructor Student()
gets invoked and prints the statement written inside it
Output
Default Constructor Invoked
Default Constructor Invoked
- Parameterized Constructor in C++
It is a constructor in C++ with parameters. This is the preferred method to initialize the data members of a class.
Example of C++ Parametrized Constructor
#include <iostream>
using namespace std;
class Student {
public:
int id; // data member (also instance variable)
string name; // data member (also instance variable)
float marks;
Student(int i, string n, float m) {
id = i;
name = n;
marks = m;
}
void display() {
cout << id << " " << name << " " << marks << " " << endl;
}
};
int main() {
Student s1 = Student(101, "Urmi", 78); // creating an object of Student
Student s2 = Student(102, "Pragati", 89);
s1.display();
s2.display();
return 0;
}
Here the class Student
has a parametrized constructor Student(int i, string n, float m)
. When the object s1
and s2
of the Student
class is created, the constructor is called with arguments to initialize the data members of the class.
Output
101 Urmi 78
102 Pragati 89
Point to remember: If we have not defined a constructor in our class, then the C++ compiler will automatically create a default constructor with an empty code and no parameters.
3. Copy Constructor in C++
It is a member function that initializes the data members of an object using another object from the same class. In other words, the copy constructor in C++ is used to copy data of one object into another.
Example of C++ Copy Constructor
#include <iostream>
using namespace std;
class Student {
public:
int id; // data member (also instance variable)
string name; // data member (also instance variable)
float marks;
Student(int i, string n, float m) { // parametrized constructor
id = i;
name = n;
marks = m;
}
// Copy constructor with a Student object as a parameter
// Copies data of the obj parameter
Student(const Student& obj) {
id = obj.id;
name = obj.name;
marks = obj.marks;
}
void display() {
cout << id << " " << name << " " << marks << " " << endl;
}
};
int main() {
Student s1 = Student(101, "Urmi", 78); // Creating an object of the Student class
Student s2 = s1; // Copy contents of s1 to s2
s1.display();
s2.display();
return 0;
}
In this program, we have used a copy constructor, Student(const Student& obj)
to copy the contents of one object of the Student
class to another.
- The parameter of this constructor has the address of an object of the
Student
class. - We then assign the values of the variables of the
obj
object to the corresponding variables of the object calling the copy constructor. This is how the contents of the object are copied. - The
const
in the copy constructor's parameterconst Student& obj
is used to ensure that the object being passed as an argument to the copy constructor is not modified within the copy constructor itself. - In
main()
, we then create two objectss1
ands2
and then copy the contents ofs1
tos2
. - The
s2
object calls its copy constructor by passing the address of thes1
object as its argument i.e.&obj = &s1
.
Output
101 Urmi 78
101 Urmi 78
Member Function vs. Constructor in C++
- The constructor's name is the same as the class's
- In the default type, there aren't any input parameters for the constructor. However, input parameters are available for copy and parameterized constructors.
- There is no return type for constructors.
- An object's constructor is invoked automatically upon creation.
- It must be shown in the class's public space i.e. only under the public access specifier.
- The C++ compiler creates a default constructor for the object if a constructor is not specified.
What is Destructor in C++?
Destructors in C++ are member functions in a class that deletes an object. They are called when the class object goes out of scope such as when the function ends, the program ends, a delete variable is called, etc.
Destructors don’t take any argument and don’t return anything. Also, destructors have the same name as their class and their name is preceded by a tilde ~
.
A destructor in C++ can be defined in two ways:
- Inside the class
Syntax
~<class-name> { // destructor definition }
Example
class ScholarHat { //class public: //access specifier ~ScholarHat() { //destructor // code } };
- Outside the class using the scope resolution operator
: :
Syntax
<class-name>: : ~<class-name>(){ // destructor definition }
Example
ScholarHat: : ~ScholarHat() { //outside the class destructor // code }
Example of Destructor in C++ Compiler
#include <iostream>
using namespace std;
class ScholarHat {
public:
// User-Defined Constructor
ScholarHat() { cout << "\n Constructor executed"; }
// User-Defined Destructor
~ScholarHat() { cout << "\nDestructor executed"; }
};
int main() {
ScholarHat t;
return 0;
}
The above C++ program shows the order of execution of the constructor and destructor when an object is created and destroyed within the main()
function. It defines a class ScholarHat
with a user-defined constructor and destructor.
Output
Constructor executed
Destructor executed
Characteristics of a Destructor in C++
- The destructor function is automatically invoked when the objects are destroyed.
- It cannot be declared static or const.
- The destructor does not have parameters.
- It has no return type.
- An object of a class with a destructor cannot become a member of the union.
- A destructor should be declared in the public section of the class.
- The programmer cannot access the address of the destructor.
Member Function vs. Destructor in C++
- Destructors have the same name as the class preceded by a tilde ~.
- Destructors don’t take any argument and don’t return anything
Summary
In this blog post, we discussed constructors and destructors in C ++. Constructors are responsible for initializing objects, while destructors are responsible for deallocating memory when an object is no longer needed. If you still have trouble understanding these concepts, enrol in ourC++ Certification.