Deallcating built in data types

What is the way to deallocate the built in data types??
Example :
class A
{
private : int a,b;

}

In main-->
A a1=new A();

Then how to deallocate the memory occupied by a1 in heap ???
First, your syntax is wrong. Second, a1 is not stored in heap. All locall variables are stored in stack. Also, you should not worry about freeing them. They are automatically freed once they go out of scope. In this case, when main ends, so does the variables.

1
2
3
4
5
6
7
8
9
10
11
12
13

int somefunc()
{
    A a1;  //Your syntax is wrong..  This is created in stack
    A *a2 = new A(); //This is created in heap

    //some codes here

    delete a2;  //you have to delete this since it was created using new in heap.

}
//After the function ends, a1 is automatically cleared
@Pravesh: Thank u.. Ya i got to know that delete a2 will delete the memory occupied the object but my confusion is can i write a destructor for the class as below..

~A()
{
delete this;
}


Can this destructor also achieves the same result as deleting an object in main using the explicit pointer to object..???
No, you can't do that.
A call to delete t where t is of the type T* do two things:
1)Call the destructor of t (T::~T if non virtual) if it exist
2)Release the memory occupied by t

If you remove line 9 of above code and make your destructor as you said, a2 destructor will never be called because when a2 go out of scope this is the destructor of A* which is called (and it doesn't exist like all the built-in type, A* is a pointer).
And not sure but i guess a1 destructor will be called recursively.
Sometimes it is legal to do delete this but this is for very special usages on an internal class which should not be used outside.

You can modify the delete behaviour if you want but you have also to modify new behaviour( i let you ask google, tons of tutos exist) but this is advanced usage.

If what you want is just automatic memory management, check std::shared_ptr and his friends (boost or c++11):
( http://en.wikipedia.org/wiki/Smart_pointer )
Topic archived. No new replies allowed.