Thursday, 16 January 2014

new operator in c++

 
1.CREATING THE OBJECT WITHOUT NEW:

myclass obj;
This creates the object for the myclass. This is similar to initializing the variable (int a;). Here myclass is the type name and obj is variable. This is static storage duration and uses the stack memory. Here the scope of the variable obj expired at the end of the block. 

2. CREATING THE POINTER TO CLASS:

myclass *obj;
This is the  pointer to class. i.e., we have created obj Pointer to myclass. you can initialize the obj in two ways
Method 1:
This is static method. This kind is passing a address of one object to initialize the pointer object.
myclass obj1,*obj2;
obj2=&obj1; //static allocation and  calls the constructor with no arguments
Method 2:
This is dynamic method. This creates a dynamic memory and need to be removed explicitly otherwise the memory leak will occur. 
myclass obj1,*obj2;
obj2=new obj1;  //Dynamic allocation and  calls the constructor with no arguments
………..
delete obj2;

3.INVALID USE OF NEW OPERATOR:
myclass obj=new myclass;
This is wrong method of creating the object. If you want to use this signature, then the obj should be a pointer to the object.

4.DIFFERENCE BETWEEN GIVING CLASS NAME AND FUNTION AFTER NEW OPERATOR:

myclass *obj=new myclass;  //Type1
myclass *obj=new myclass();  //Type2

Both are same. If we fail to give the paranthesis then the compiler will take it as  an constructor with no parameter.

5.USING NEW OPERATOR FOR BASIC DATATYPE:

int *a;
a=new int(5);
Here the memory for a is created at run time, and the a is initialized with value of 5 at runtime. a is stored under the heap memory and a is to be deallocated explicitly.

6.HEAP MEMORY AND STATIC MEMORY:

Heap memory for the dynamic memory allocation.
Stack memory is for the static memory allocation.




#include<iostream>
using namespace std;

class new_demo
{

};

int main()
{
   cout<<"Creating Object without new!!!\n";
   new_demo obj1;

   cout<<"Creating a pointer to class\n";
   new_demo *obj_pointer;

   cout<<"Assigning a pointer to class with obj1\n";
   obj_pointer=&obj1;

   cout<<"Creating a object with new operator \n";
   obj_pointer=new new_demo;

   cout<<"Wrong: Creating a object with new operator and assigning to a normal object instead of pointer \n";
   // obj1=new new_demo;  Obj is object here we cannot use new for that

   return 0;

}

Output:

Creating Object without new!!!
Creating a pointer to class
Assigning a pointer to class with obj1
Creating a object with new operator
Wrong: Creating a object with new operator and assigning to a normal object instead of pointer