Constructor and Destructor

Constructor and Destructor

In this part you will learn: 1. What are Constructor and Destructor? 2. Types of Constructor 3. Syntax of Constructor and Destructor 4. Writing program with constructor and destructor 5. Showing output Constructor Constructor is a function of the class which is called at initialization or declaration of an object. To initialize values to the members of the function we use this function. For example if we have a class named “fraction” having num and denom as discussed earlier and we want to initialize every fraction created a value ‘zero’. Now as we know basic rule of mathematic that the denominator can’t be zero. So in our constructor we will assign zero to our numerator (num) and one to our denominator (denom). And how it will be done we will discuss it in detail later. There are basic three types of Constructors, namely • Default(implicit) constructor. • Overloaded constructor. • Copy constructor The first two types of constructors i.e. default and overloaded constructors have almost same functionality whereas copy constructor is a bit different. We will discuss that in the next section of this book. For now let us focus on the first two types of constructors. In Default constructor same values are set for all the objects of that type, i.e. whenever a default constructor is called for an object a specific value which is specified by the programmer is assigned to the particular member of the object. Whereas in overloaded constructor, the value we want to assign to the members is passed to the constructor as its parameter and then assigned to the member variables of that class. Syntax
  1. Class_Name()
  2. {
  3. //Assignment_of_values_to_member variables
  4. }
Note: In case of overloaded constructor the values will be passed to the function as parameter. Destructor Whenever the scope of an object ends, its destructor function is called. In case of simple variable destructor is not really important, but if we are dealing with pointers, more precisely dynamic memory allocation. Then it is the responsibility of the programmer to deallocate(free) the memory. For example, if we create an array using a member pointer variable of a class in the constructor or outside of it. Then it is the responsibility of the programmer to deallocate that memory otherwise it will be a case of memory leakage, which means that even after the termination of program, that particular part of memory won’t be available for usage which is a bad programming practice. Syntax
  1. ~Class_Name()
  2. {
  3. //deletion of the dynamic memory allocated in the program
  4. }
Note: To differentiate between a constructor and a destructor we use ~ symbol in c++ language. Point to Ponder As we know that we have already written many class definitions without even using constructor and destructor. How to work without them? The answer is, every class has a by default constructor and destructor which is usually empty. i.e. when an object of a class is to be created or destroyed, its respective constructor or destructor is called but nothing happens. So if we initialize an object of a class without constructor, its members are assigned garbage value. Program with Constructor and Destructor Let us take an example of sets to explain the working of constructor and destructor. Here in this example we will have a class named “sets” containing two member variables size and ele, in which ele is a pointer to integer and size is a simple integer. Note: In this example I have made the member variable’s access Public for the sake of simplicity because right now we are focusing on constructor and destructor, as we have discussed earlier, we can make them private and use getters and setters to access them Basic Step:
  1. #include<iostream>
  2. #include<conio.h>
  3. using namespace std;
These two are the most common and basic lines of a c++ program. The first one iostream is used to grant us most of the basic functions of C++ like Input and Output functions. The second one conio.h means console input output, the black screen we see is the console. Using namespace std; provides us an ease of using all the library functions without specifying that this function belongs to standard library. Without including it, we have to write ‘std’ with all the built-in functions. Class
  1. class set
  2. {
  3. public:
  4. int *ele;
  5. int size;
  6.  
  7. set(){
  8. cout << endl << "Default constructor called" << endl;
  9. size = 0;
  10. ele = NULL;
  11. }
  12.  
  13. set(int n){
  14. cout << endl << "Overloaded constructor called" << endl;
  15. size = n;
  16. ele = new int [size];
  17. }
  18.  
  19. ~set(){
  20. cout << endl << "Destructor called" << endl;
  21. if (size > 0)
  22. delete[]ele;
  23. ele = NULL;
  24. }
  25. };
The above given code is the definition of class “set” which has 2 member variables ele and size. I have made two different types of constructors and a destructor. The first constructor is the default constructor it will be called when the caller won’t add any parameter to initialization, in this constructor ele will be assigned value NULL and size would be declared as zero. In the second type of constructor which is an overloaded constructor the size will be passed to the function as a parameter in the variable n, in the body of function we will assign the value of “n” to the member variable “size” and then we will create an array of size equal to the value stored in variable “size”. In this way, the array of size specified will be created while initialization. Note: This is an example of only two variables, we can add as many variables as we want and assign values to each member variable using this technique. Moreover there can be more than one overloaded constructor, each with its own specification according to requirement. Main
  1. int main()
  2. {
  3. {
  4. set a;
  5. set b(5);
  6. }
  7. system("pause");
  8. }
The main part of our program is pretty simple. I have enclosed the objects a and b in a pair of curly brackets, the reason behind this is that since we want to observe the working of constructor and destructor. If I had created the objects directly in main then we couldn’t have observed the calling of destructor. Since in current scenario the scope of objects is the inner pair of curly brackets, as soon as we will come out of the inner curly brackets, the destructor will be called. And the program will pause at the statement “ system("pause");”. At first when “set a;” will execute, since it doesn’t have any parameter, default constructor will be called and it will print on the screen that "Default constructor called" in the next statement overloaded constructor will be called creating an array of size 5 and assigning value 5 to the member variable size and it will print on the console that "Overloaded constructor called". Finally when the scope of these objects will end destructor will be called for both of them. For the object a, there won’t be any memory deletion since it comes under the condition that if size is greater than zero. But in case of object b, as its size is greater than zero first the memory will be deleted, after that it will be pointed to NULL which will happen with object a too. Since destructor is called twice i.e. for object a and b it will print "Destructor called" twice. Output picture viewer

Add new comment