Comprehensive Java Course (4 Blogs)

How To Implement Constructor And Destructor In C++?

Last updated on Sep 26,2020 23.6K Views

How To Implement Constructor And Destructor In C++?

C++ can easily be one of the most important programming language, if you ask the current programming world. One of the many reasons for it is the features it offers. This article will discuss one such feature that is constructor and destructor in C++. Following Pointers will be covered in this article,

So let us get started with this article on Constructor and Destructor in C++

Constructors And Destructors In C++

Constructor

A Constructor is a member function of a class. It is mainly used to initialize the objects of the class. It has the same name as the class. When an object is created, the constructor is automatically called. It is a special kind of member function of a class.

Difference Between Constructor and Other Member Functions:

1. The Constructor has the same name as the class name.
2. The Constructor is called when an object of the class is created.
3. A Constructor does not have a return type.
4. When a constructor is not specified, the compiler generates a default constructor which does nothing.
5. There are 3 types of constructors:

  •  Default Constructor
  • Parameterized Constructor
  • Copy constructor

A constructor can also be defined in the private section of a class.

Moving on with this article on Constructor and Destructor in C++

Default Constructor

A Default constructor is a type of constructor which doesn’t take any argument and has no parameters.

Here is an Example Code

#include <iostream>
using namespace std;
class test {
public:
int y, z;
test()
{
y = 7;
z = 13;
}
};
int main()
{
test a;
cout <<"the sum is: "<< a.y+a.z;
return 1;
}
Output:

Output- Constructor and Destructor in C++- Edureka

Explanation:

The above program is a basic demo of a constructor in c++. We have a class test, with two data members of type int called y and z. Then we have a default constructor, which assigns 7 and 13 to the variables y and z respectively.
The main function has an object of class test called a. When this object is created the constructor is called and the variables y and z are given values. The main function has a cout statement or a print statement. In this statement, the sum is printed. With respect to the object of the class, we access the public members of the class, that is, a.y gives the value of y and the same for z. We display the sum of y and z.
The default constructor works this way. When we do not provide a default constructor, the compiler generates a default constructor which does not operate.
Next, let us take a look at parameterized constructor.

Moving on with this article on Constructor and Destructor in C++

Parameterized Constructor

Passing of parameters to the constructor is possible. This is done to initialize the value using these passed parameters. This type of constructor is called a parameterized constructor.
The constructor is defined as follows:

test(int x1) 
{ 
x = x1;
} 

There is a parameter that is passed to the constructor. The value is passed when the object is created in the main function as shown below.

test t(10);

Inside the main function, we create an object of class test and pass the value of the variable.

Here is an Example Code:

#include <iostream> 
using namespace std;   
class test { 
public: 
int x; 
test(int x1) 
{ 
x = x1; 
}      
int getX() 
{ 
return x; 
}     
};   
int main() 
{    
test a(10); 
cout << "a.x = " << a.getX() ; 
return 0; 
}

Output
Output- Constructor and Destructor in C++- Edureka

 

Explanation

The above program is a basic demo of a parameterized constructor. We have a class test, with one data member of type int called x. Then we have a parameterized constructor, with x1 as the parameter passed from the main function, while object creation. The constructor assigns data member x the value of x1. We have a getX function next that simply returns the value of x.
The main function has an object of class test called a. There is a value associated with this object, this is a parameter.

test a(10);

We then print the value of x using the member function getX. We call the function with respect to the object of the test class called a.

Moving on with this article on Constructor and Destructor in C++

Copy Constructor

A Copy Constructor is a Constructor which initializes an object of a class using another object of the same class.

Here is an Example Code:

#include<iostream>
using namespace std;
class test
{
private:
int x;
public:
test(int x1)
{
x = x1;
}
test(const test &t2)
{
x = t2.x;
}
int getX()
{
return x;
}
};
int main()
{
test t1(7); // Normal constructor is called here
test t2 = t1; // Copy constructor is called here
cout << "t1.x = " << t1.getX();
cout << "nt2.x = " << t2.getX();
return 0;
}
Output

Output- Constructor and Destructor in C++- Edureka

Explanation

The above program is a basic demo of a copy constructor. We have a class test, with a private data member of type int called x. Then we have a parameterized constructor, which assigns 7 to the variables x. We have a copy constructor, which instantiates the value of t2 with the value of t1.

test(const test &t2)
{
x = t2.x;
}

Address of t2 is sent which holds the value of t1, and is assigned to x. There exist a get function which returns the value of x. The main function has an object of class test called t1 . There is a value associated with this object, this is a parameter.

test t1(7);

The main function has another object of class test called t2 . This is initialized by using the t1 variable and the copy constructor is called here.

test t2=t1;

Lastly, the get function is called with respect to t1 and t2 to get the value of x.

cout << "t1.x = " << t1.getX();
cout << "nt2.x = " << t2.getX();

Next, we look at destructors.

Moving on with this article on Constructor and Destructor in C++

Destructor

Destructors are another type of member function that is responsible for destroying or deleting the object. It frees up space occupied by the object after it is no longer needed. A Destructor is called automatically when the object is out of scope and no longer needed. A Destructor has the name same as the class name, but the only difference is that the name is preceded by a tile(~).

~test()

There has to be only one Destructor in a class. A Destructor has no return type and no parameters. If we do specify a destructor in class then, the compiler creates a default destructor. The default destructor works fine unless memory is dynamically allocated or pointer is declared in the class.
The Destructor is called when,

  • A function ends.
  • A program ends.
  • A block that contains the local variable ends.
  • A delete operator is called in the program.

Here is an Example Code:

#include <iostream>
using namespace std;
class test {
public:
int y, z;
test()
{
y = 7;
z = 13;
}
~test(){ }
};
int main()
{
test a;
cout <<"the sum is: "<< a.y+a.z;
return 1;
}
Output

Output- Constructor and Destructor in C++- Edureka

The only difference in this code is the presence of a destructor that is used to destroy the created object after the completion of execution of the program.

Moving on with this article on Constructor and Destructor in C++

Virtual Destructor

The only variation to the destructor is making the destructor virtual. This is done when we have inheritance. During inheritance, the normal destructor behaves in an undefined manner. To fix this problem, the base class destructor has to be declared as virtual.

class base {
public:
base()
{ cout<<"base Constructor n"; }
virtual ~base()
{ cout<<"base destructorn"; }
};

Making the base virtual ensures proper deletion of the objects.

Thus we have come to an end of this article on ‘Constructor and Destructor in C++’. If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this blog  and we will get back to you as soon as possible.

Comments
0 Comments

Join the discussion

Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.