Sunday, February 13, 2011

New and delete Operators:


New and delete Operators:
             As we know that the process of allocating and freeing memory at run time is called Dynamic Memory Allocation. This conserves the memory required by the program and returns this valuable resource to the system once the use of reserved space is utilized. In C, the functions like calloc(), malloc(), free(), realloc() are used for memory management at run time. C++ supports two new unary operators new and delete for memory management at run time along with these C’s functions. An object can be created by using new and destroyed by using delete.
Syntax for new:
   pointer_variable=new data_type;
            Where pointer_variable is predefined pointer of type data_type and data_type is user-defined or built in data type of C++. The new operator allocates sufficient memory to hold a data object of type data_type and returns the address of the object. The pointer variable holds the starting address of allocated memory.
Examples:
int *ptr;
ptr=new int;
    The above statement allocates two bytes of memory and is stored by pointer variable ptr.

Characteristics:
Ø  Memory can be initialized using new operator. This is done as
         Pointer _variable= new data_type(initial_value);
       e.g. int *p;
                p=new int(35);
        will allocates two bytes of memory and 35 is allocated at this memory initially.  
Ø  new can be used to allocate a memory space for data types including user defined types such as arrays, structures and classes. Its syntax is
         pointer_variable=new data_type[size]; // for array
         e.g.
                int *p;
              p=new int[100];
         will allocates 200 bytes memory and starting address is stored at pointer variable p.

Advantages of new operator over the function malloc()
Ø  It automatically computes the size of the data object while we need to use sizeof operator in the case of malloc() function.
Ø  It is possible to initialize the object while creating the memory space.
Ø  It automatically returns the correct pointer type, so that there is no need to use a type caste. In syntax of malloc() function
                    ptr_variable=(data_type*) malloc(size_of_block);
     data_type within () is for type casting which is not needed in the case of new operator.


Delete:
If a program reserves many chunks of memory using new, eventually all the available memory will be reserved and the system will crash. To ensure safe and efficient use of memory, the new operator is matched by a corresponding delete operator. This operator returns the memory to the operating system when a data object in no longer needed. Thus, delete operator is used to release the memory space for reuse by destroying the object when it is no longer needed. The syntax
          delete pointer-variable;   // general syntax
          delete [] pointer-variable;  // in case of array
        
        An example, a program which asks for a number of students at run time and according to the number of students in a class, the program reserves the memory to store percentage of each student and finally calculates average percentage of class.
#include<iostream.h>
void main()
  {
  int num,*ptr;
  float sum=0;
  cout<<"How many number of students?"<<endl;
  cin>>num;
 ptr=new int[num];
 cout<<"Enter each students marks"<<endl;
 for(int i=0;i<num;i++)
   {
   cin>>*(ptr+i);
   sum+=*(ptr+i);
   }
   float avg= sum/num;
   cout<<"The average is  "<<avg;
   delete []ptr;
    }

const:
 This is C++ qualifier used for creating symbolic constant. Its syntax is
const data_type variable_name= value;
e.g.   const int size=10;
It specifies that the value of a variable (here, size) will not change throughout the program. Any attempt to alter the value of a variable defined with this qualifier will give error message by compiler. It is used for variables which do not change throughout the program like PI while calculating area of circle. In C++, the variable defined with this qualifier const should be initialized.

Enumeration:
   The dictionary meaning of enumeration is counting, go through a list of articles naming them one by one. The process enumeration provides user defined data type, called enumerated data type which provides a way for attaching names to numbers. The syntax is
enum tag_name {name1, name2, name3, ….};
e.g.  enum flag{false, true};
        enum colour{red, blue, green, white};
Here, colour is enumerated data type whose permissible values are red, blue, green and white. Here, possible values red, blue, green and white are also called enumerators. These enumerators are attached with numbers 0,1,2 and 3 (i.e. o for red, 1 for blue and so on). Variables can be defined using this enumerated data type. These variables store only those values defined while defining enumerated data type.
e.g.
       colour foreground;
       foreground=red // ok
       foreground=yellow; // not ok as yellow is not possible value for data type colour

By default, the enumerators are assigned integers values starting with o for the first enumerator, 1 for second and so on. These can be explicitly assigned by the programmer as following.
    enum colour{red=7,blue, green, white};  // here, blue=8, green=9 and white=10

Characteristics:
Ø  Although the enumerated data types are treated internally as integers, C++ does not permit an int value to be automatically converted to an enum value. E.g.
           colour foreground=2; // error
           colour foreground= (colour)2 // ok
Ø  An enumerated value i.e. enumerator can be used in place of an int value. E.g.
          int num= red; // ok
Ø  The enumeration provides an alternative means for creating symbolic constants. The enumerator’s value can be changed in the program.
Ø  The anonymous enums (without enum_tag_name) can be created in C++.
e.g. enum {red,blue,green,white};

An example:
#include<iostream.h>
void main()
 {
 enum days{sun,mon,tue,wed,thu,fri,sat};
 days day1,day2;
 int mid_day;
 day1=sun;
 day2=sat;
 mid_day=wed;
cout<<"day1= <<day1<<endl<<"day2="<<day2<<endl<<"Middle="<<mid_day;
}

Output:
day1=0
day2=6
Middle=3

An another example which asks a number and test it for even or odd.
#include<iostream.h>
#include<conio.h>
void main()
 {
  clrscr();
  int num;
  enum flag{false, true};
  flag even;
  cout<<"Enter a number to check even or odd"<<endl;
  cin>>num;
  if(num%2==0)
       even=true;
    else
      even =false;
 if(even)
   cout<<"The number is even";
   else
    cout <<"The number is odd";
 getch();
 }

No comments:

Post a Comment