Dynamic Operators and Constructors
When constructor and destructor are executed they internally use new and delete operators to allocate and de-allocate memory. Dynamic construction means allocation of memory by constructor for objects, and dynamic destruction means releasing memory using the destructor. Consider the following program that explains the use of new and delete operators with constructor and destructor.
9.22 Write a program to use new and delete operators with constructor and destructor. Allocate memory for the given number of integers. Also release the memory.
Explanation: In the above program, class num is declared with two variables and they are integer pointer *x and integer variable s. The class also contains constructor and destructor. The responsibility of constructor is to allocate memory using new operator for a given number of integers by the user. The non-member function number() is used to input number of elements through the keyboard and the entered numbers are stored in the variable s. The variable s is used with the new operator to allocate memory. The memory is allocated to the pointer x.
The member function input() reads elements and the for loop repeats the statement cin>>x[h] for s (number of total elements) times. The x[h] is used like array. The x is the starting address and h indicates the successive locations. The address of pointer x remains unchanged. The value of h is added to value of x. In this way, all these numbers are stored in continuous memory locations. If you are still confused how successive memory locations are accessed, go through the pointer arithmetic operations.
The sum() function is used to perform addition of all the entered numbers and displays the same on the screen. The destructor is finally executed which releases the memory using delete operator.
Tip: In the above program, if we remove the operators new and delete, the program will work successfully. However, this is suitable for small programs, developed for demonstration purpose. In real application, it needs large amount of memory to be allocated or released. Hence, it is very essential to check the memory before doing the process. For example, when any program is loaded in the memory, the operating system checks for available system resources that are sufficient enough to load the requested application by the user. In such a case, the operating system checks memory resources and if memory is insufficient, the compiler displays the same message to the user.