Site icon DataFlair

Learn Constructor and Destructor in C++ in 6 Min.

Free C++ course with real-time projects Start Now!!

The terms constructor and destructor in C++ go hand in hand. Constructors are called each and every time you create an object and a destructor is called every time you destroy an object. Today, we come up with this complete tutorial dedicated to constructors and destructor in C++, which will help you to master this concept with syntax and examples.

Before we begin, revise the concept of classes and objects in C++.

Constructor and Destructor in C++

Constructor and Destructor in C++ are basically subtopics of Classes and Objects. It is safe to say that both of these topics are important features offered by Classes and Objects that help you dive deeper into exploring the depth of object-oriented programming. We will cover each and every topic in detail.

1. What are Constructors in C++?

Till now, we studied that after defining the data members and member functions of a class, we need to create instances of the class, that is, objects through which we can access the members of the class. We do this in order to reserve memory in the computer system for the class data type.

There is an important feature offered by C++ that comes along with classes and objects. They are called constructor and destructor in C++.

In programming terminology, C++ constructor is nothing but a special class function that allows you to initialize the value of each and every object associated with that class.

The C++ compiler automatically calls the constructor after the creation of an object.
The same purpose which a constructor in C++ serves can be served by any other member function of that class but the only difference is that we need to call that member function in the program explicitly.

Key takeaway: It is important to note that the constructor in C++ has the same name as that of the class and it is invoked whenever the object of that class is created.

From the above discussion, we infer that constructors not only saves time in implementing classes but also serves as a unique function making C++ ubiquitous.

Do you know how to implement Data Abstraction in C++?

1.1 Syntax of Constructor in C++

In this portion, we will cover the declaration and definition part of the constructor.

We define a C++ constructor in a similar way as that of any other member function of a class.

Definition of the function can either be given inside or outside the class (With the help of scope resolution operator ‘::’ ).

Always remember, the name of the constructor in C++ should essentially be the same as that of the class without a return type, otherwise it would result in a compilation error.

class Class_name
{
public:
int variable;
class_name() // Declaring a constructor
// BODY OF THE CLASS 
}
};
int main()
{
Class_name c; // Creation of an object
return 0;
}
class Class_name
{
public:
int variable;
class_name() // Defining a constructor
{
variable = 0; // Initialzing the object to 0
}
};
int main()
{
Class_name c; // Creation of an object
return 0;
}
class Class_name
{
public:
int variable;
class_name() // Declaring a constructor
// BODY OF THE CLASS 
}
};
//Defintion outside the class
Class_name :: Class_name()
{
variable = 0;
}
int main()
{
Class_name c;
return 0;
}

1.2 Properties of Constructor in C++

So far, we have understood the basic meaning of what is constructor in C++ and what it does. Before we proceed any further, it is important to note some of its characteristics in order to avoid any sort of mistakes that we might commit in the future:

  1. The name of the constructor should be the same as that of the class.
  2. A constructor should not have any return type.
  3. A constructor is automatically invoked as soon as we create an object.
  4. A constructor is associated with the class.
  5. A constructor may have default parameters or arguments.
  6. We cannot use the const keyword along with the constructor name, although C++ allows the constructor to be invoked for an object of constant value.
  7. A constructor does not have the provision to refer to its own address.

It’s time to discuss Polymorphism in C++

1.3 Types of Constructor in C++

There are 5 types of C++ constructors Although there are three major types of constructors, that is, The default constructor, The parametrized constructor, and The copy constructor, we will discuss the other two types in detail as well.

Let us discuss each type of constructor in detail one by one:

1.3.1 Default Constructor

A default constructor is nothing but a type of constructor that has no arguments or parameters. It is important to note that no object of a class is created without a constructor. If the programmer does not specify initial values, then this task is done by the C++ compiler.

The compiler automatically provides a default constructor for creating the objects with some temporary values if the programmer does not include any constructor at the time of programming.

Syntax

Class_name()
{
// Constructor definition
}

Example of Default Constructor in C++

Here is a C++ program that illustrates the use of a default constructor:

#include <iostream> 
using namespace std; 

class DataFlair 
{ 
public: 
int value; 

DataFlair() // Definition of the default constructor 
{ 
value = 50; 
} 
}; 

int main() 
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

DataFlair d; // The constructor
cout<<"The value stored in the variable is: " <<d.value<<endl; 
return 0; 
}

Code-

Output-

1.3.2 Parametrized Constructor

As the name itself suggests, a parameterized constructor is nothing but a constructor with arguments or parameters. They prove to be of immense significance when the programmer wishes to initialize various data members of different objects with different values after their creation.

There are basically two ways to pass initial values to the constructor in C++:

This is how you would explicitly call the constructor:

Class_name object_name = Class_name ( parameters );

For instance,

Employee e = Employee( 1001, “Mark”, 22 );

This is how the constructor is implicitly called:

Class_name object_name ( parameters);

For instance,

Employee e ( 1001, “Mark”, 22 );

Syntax

class_name( argument1, argument2, … , argumentN )
{
// Constructor definition
}

Example of Parameterized Constructor in C++

Here is a C++ program that illustrates the use of a parameterized constructor:

#include <iostream> 
using namespace std; 

class Coordinates 
{ 
private: 
int x, y, z; 

public: 
Coordinates(int x1, int y1, int z1) // Definition of the parameterized constructor to access the private members of the class
{ 
x = x1; 
y = y1; 
z = z1;
} 
int displayX() 
{ 
return x; 
} 
int displayY() 
{ 
return y; 
} 
int displayZ() 
{ 
return z; 
} 
}; 

int main() 
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

Coordinates p(2, 4, 7); // Calling the constructor

// Accessing values using the constructor 
cout<<"The x coordinate is: " <<p.displayX()<<endl;
cout<<"The y coordinate is: "<<p.displayY()<<endl; 
cout<<"The z coordinate is: "<<p.displayZ()<<endl; 

return 0; 
}

Code-

Output-

After understanding the above-written program on parametrized constructors in C++, let us discuss the advantages of using parametrized constructors.

  1. It helps the programmer to achieve constructor overloading.
  2. It serves as an easy way to initialize the values of the various data members of the class.

1.3.3 Copy Constructor

In a copy constructor, you can initialize an object with the help of another object. In other words, if we have 2 objects o1 and o2 and we want to copy the values of o1 to o2, we use the copy constructor to perform this task.

Syntax

This is how you would declare a copy constructor:

Class_name object1; // Creation of 1st object
Class_name object2( object1 ); // Use of copy constructor

Another way of declaring a copy constructor is:

Class_name object2 = object1;

For instance,

Employee e2 (e1)

Or

Employee e2 = e1;

Example of Copy Constructor in C++

Here is a C++ program that illustrates the use of a copy constructor:

#include<iostream> 
using namespace std; 

class Coordinates 
{ 
private: 
int x, y, z; 
public: 
Coordinates(int x1, int y1, int z1) 
{
x = x1; 
y = y1;
z = z1; 
} 

Coordinates(const Coordinates &c2) // Definition of the copy constructor 
{
x = c2.x;
y = c2.y; 
z = c2.z;
}

int displayX() 
{ 
return x; 
} 
int displayY() 
{ 
return y; 
}
int displayZ()
{
return z;
} 
}; 

int main() 
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

Coordinates c1(10, 20, 50); // Calling the original constructor
Coordinates c2 = c1; // Calling the copy constructor

// Accessing the values using both the constructors
cout<<"Values of coordinates using original constructor: " << c1.displayX() << "\t" << c1.displayY() << "\t" << c1.displayZ()<<endl; 
cout<<"Values of coordinates using copy constructor: " << c2.displayX() << "\t" << c2.displayY() << "\t" << c2.displayZ()<<endl;

return 0; 
}

Code-

Output-

1.3.4 Constructor with Default Arguments

C++ gives you the provision to define constructors with default arguments.

Here is a C++ program that illustrates the use of a constructor with default arguments:

#include<iostream>
using namespace std;

class Average
{
// private by default
float min, max, result;
public:
Average(float m1, float m2 = 100); // Default argument
void compute();
};
Average :: Average(float m1, float m2)
{
max = m1;
min = m2;
}
void Average :: compute()
{
cout<<"The minimum value is: "<<min<<endl;
cout<<"The maximum value is: "<<max<<endl;
result = (min + max) / 2;
cout<<"The average of the two values is: "<<result<<endl<<endl;
}

int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

Average a1(58,85.5);
Average a2(60, 95.25);
Average a3(80,100);
a1.compute();
a2.compute();
a3.compute();

return 0;
}

Code-

Output-

1.3.5 Overloaded Constructor

It is important to note that a class can have a various number of constructors in C++. It is evident that all the constructors in the class have the same data members as that of the class but the difference comes with different arguments or parameters used. This feature is known as Constructor overloading.

In simple words, when we define more than one constructor in a class with different parameters, the constructor is said to be overloaded.

Key takeaway: While creating an object, we necessarily need to pass parameters to instruct the C++ compiler to invoke the constructor.

Example of Overloaded Constructor in C++

Here is a C++ program that illustrates the use of an overloaded constructor:

#include<iostream>
#define PI 3.14
using namespace std;

class Circle
{
float radius, circumference;
public:
Circle() // Definition of a Default constructor
{
radius = 0;
}
Circle(int r) // Definiton of a Parameterized constructor
{
radius = r;
}
Circle(Circle &c) // Defintion of a Copy constructor
{
radius = c.radius;
}
void compute()
{
circumference = 2 * PI * radius;
}
void display()
{
cout<<"The radius of the circle is: "<<radius<<endl;
cout<<"The circumference of the circle is: "<<circumference<<endl<<endl;
}
};

int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

Circle c1(3);
Circle c2(c1);
Circle c3;
c1.compute();
c2.compute();
c3.compute();
c1.display();
c2.display();
c3.display();

return 0;
}

Code-

Output-

C++ Data Structures – The Secret Behind A Successful Programmer  

2. What is Destructor in C++?

As the name itself suggests, we use a destructor to destroy an object that has been created by a constructor. In other words, destructors in C++ are basically member functions that we use in order to destroy the objects created by the constructor. Just like constructors, the name of a destructor is same as that of a class. The name of a destructor is preceded by the tilde sign ‘~’

Syntax

~ Class_name()
{

};

2.1 Example of Destructor

Here is a C++ program that illustrates the use of a destructor:

#include<iostream>
using namespace std;

class Numbers
{
//private by default
int x, y;
public:
Numbers(int a, int b);
void display();
~Numbers();
};
Numbers :: Numbers(int a, int b)
{
x = a;
y = b;
} 
void Numbers :: display()
{
cout<<"The numbers are: "<<x<<" and 
"<<y<<endl;
}
Numbers :: ~Numbers()
{
cout<<"This is how a Destructor is called. "<<endl;
}
int main()
{

cout<<"Welcome to DataFlair tutorials!"<<endl<<endl;

Numbers n(10,20);
n.display();

return 0;
}

Code-

Output-

2.2 Properties of C++ Destructor

Let us briefly discuss some of the properties of destructors in C++:

  1. The name of a destructor is the same as that of the class preceded by the tilde sign ‘~’.
  2. We cannot provide any parameters or arguments in the destructor.
  3. A destructor does not have a return type.
  4. The concept of Inheritance and the use of destructors cannot be implemented simultaneously.
  5. C++ does not allow the overloading of destructors.
  6. Every destructor is automatically invoked in a class. It is generated by the C++ compiler automatically.
  7. There cannot be more than one destructor inside a class.
  8. The implementation of virtual destructors is possible in C++.

3. Quiz on Constructor and Destructor in C++

Time limit: 0

Quiz Summary

0 of 15 Questions completed

Questions:

Information

You have already completed the quiz before. Hence you can not start it again.

Quiz is loading…

You must sign in or sign up to start the quiz.

You must first complete the following:

Results

Quiz complete. Results are being recorded.

Results

0 of 15 Questions answered correctly

Your time:

Time has elapsed

You have reached 0 of 0 point(s), (0)

Earned Point(s): 0 of 0, (0)
0 Essay(s) Pending (Possible Point(s): 0)

Categories

  1. Not categorized 0%
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  1. Current
  2. Review / Skip
  3. Answered
  4. Correct
  5. Incorrect
  1. Question 1 of 15
    1. Question

    #include <iostream>

     

    using namespace std;

    class Data{

        public:

        int x;

        Data()

        {

            cout<<“Hello”;

        }

    };

    int main()

    {

        Data d;

        return 0;

    }

    Correct
    Incorrect
  2. Question 2 of 15
    2. Question

    #include <iostream>

     

    using namespace std;

    class Data{

        int x;

        public:

        int y;

        Data()

        {

            x=10;

            cout<<x;

        }

    };

    int main()

    {

        Data d;

        return 0;

    }

    Correct
    Incorrect
  3. Question 3 of 15
    3. Question

    #include <iostream>

     

    using namespace std;

    class Data{

        int x;

        public:

        int y;

    };

    int main()

    {

        Data d;

        d.x=5;

        d.y=7;

        cout<<d.x<<d.y;

        return 0;

    }

    Correct
    Incorrect
  4. Question 4 of 15
    4. Question

    #include <iostream>

     

    using namespace std;

    class Data{

        int x;

        public:

        int y;

        Data(){

            x=5;

            cout<<x;

        }

    };

    int main()

    {

        Data d;

        d.y=7;

        cout<<d.y;

        return 0;

    }

     

    Correct
    Incorrect
  5. Question 5 of 15
    5. Question

    #include <iostream>

     

    using namespace std;

    class cons{

        int x;

        public:

        int y;

        cons(int z)

        {

            x=z;

            cout<<x;

        }

        cons()

        {

            y=10;

            cout<<y;

        }

    };

    int main()

    {

        cons c;

        return 0;

    }

    Correct
    Incorrect
  6. Question 6 of 15
    6. Question

    #include <iostream>

     

    using namespace std;

    class cons{

        int x;

        public:

        int y;

        cons(int z)

        {

            x=z;

            cout<<x;

        }

        cons()

        {

            y=10;

            cout<<y;

        }

    };

    int main()

    {

        cons c2(4);

        return 0;

    }

     

    Correct
    Incorrect
  7. Question 7 of 15
    7. Question

    #include <iostream>

     

    using namespace std;

    class cons{

        int x;

        public:

        int y;

        cons(int z)

        {

            x=z;

            cout<<x;

        }

        cons()

        {

            y=10;

            cout<<y;

        }

    };

    int main()

    {

        cons c2(4);

        cons c1;

        return 0;

    }

     

    Correct
    Incorrect
  8. Question 8 of 15
    8. Question

    #include <iostream>

     

    using namespace std;

    class cons{

        public:

        int x;

        int y;

        cons(int z)

        {

            x=z;

        }

        cons()

        {

            y=5;

        }

    };

    int main()

    {

        cons c2(20);

        cons c1;

        cons c3 =c2;

        cout<<c3.x;

        return 0;

    }

     

    Correct
    Incorrect
  9. Question 9 of 15
    9. Question

    #include <iostream>

     

    using namespace std;

    class cons{

        public:

        char x;

        int y;

        cons(int z)

        {

            x=’A’;

        }

        cons()

        {

            y=10;

        }

    };

    int main()

    {

        cons c2(20);

        cons c1,c3,c4;

        c3=c4=c2;

        cout<<c4.x;

        return 0;

    }

     

    Correct
    Incorrect
  10. Question 10 of 15
    10. Question

    #include <iostream>

     

    using namespace std;

    class cons{

        public:

        char x;

        int y;

        cons(char c)

        {

            x=c;

        }

        cons()

        {

            y=10;

        }

    };

    int main()

    {

        cons c2(‘A’);

        cons c1,c3,c4;

        c3=c4=c2;

        cons c5(‘B’);

        cout<<c4.x<<c5.x;

        return 0;

    }

    Correct
    Incorrect
  11. Question 11 of 15
    11. Question

    What are different types of constructors?

    Correct
    Incorrect
  12. Question 12 of 15
    12. Question

    Identify which of the following could be a call of destructor?

    Correct
    Incorrect
  13. Question 13 of 15
    13. Question

    Which of the following statements is true with respect to constructor and destructor both?

    Correct
    Incorrect
  14. Question 14 of 15
    14. Question

    What is a valid condition to trigger a destructor call?

    Correct
    Incorrect
  15. Question 15 of 15
    15. Question

    What is not true about copy constructor?

    Correct
    Incorrect

4. Summary

In this tutorial, we discussed Constructors and Destructors in C++ in detail. We started off with trying to understand the meaning and significance of constructors. Thereafter, we discussed the various types of constructors in detail with illustrative C++ programs. We even discussed the characteristics of both constructors and destructors in C++ to avoid missing out on the slightest concept.

Don’t forget to check Interfaces in C++ (Abstract Class)

We hope you had a great time reading this tutorial. If you have any further queries, feel free to leave a comment below.

Exit mobile version