If you are worried about memory leaks, then consider using smart pointers - never use new or delete ever again.
Why do you have a private destructor?
Edit:
Sorry, I should have done this before posting ....
I just read up about private destructor's - it seems they are handy for reference counted objects - which is what smart pointers are, but you don't seem to be doing that.
A private destructor doesn't make sense unless the constructors are also private. There's little value in being able to create an object if you can't destroy it. There might be a few very specific circumstances where you might want a private dtor, but frankly I can't think of any.
(Even reference counted objects work fine with a public dtor)
Is there any need of calling obj->~Test() ?
No. delete will automatically call dtors on all objects in the array. You must not call them explicitly... and instead, you should delete the object (since it was allocated with new):
1 2 3 4
void destroy(Test *obj)
{
delete obj;
}
But even this might fail because now delete is calling your dtor instead of your destroy() friend function.
> private destructor are used to make only dynamic objects. Because the compiler can't invoke the destructor.
This (public constructors and a private destructor) is what Scott Myers recommends.
Item 27: More Effective C++.
...
An alternative is to declare all the constructors private. The drawback to that idea is that a class often has many constructors, and the class's author must remember to declare each of them private. This includes the copy constructor, and it may include a default constructor, too, if these functions would otherwise be generated by compilers; compiler-generated functions are always public. As a result, it's easier to declare only the destructor private, because a class can have only one of those.
...
I've generally favoured the use of private constructors and a public destructor (in conjunction with public, static factory functions or a helper friend factory class) to exercise control over how clients create objects. It makes the task of the class author a bit harder; but it also provides finer control (for instance, the class author can enforce use of smart pointers).
I have 1 more question:
Assume: destructor is Public.
1 2 3 4
~Test()
{
delete[] arr;
}
Now, will the data member (created on stack like int a here) be also deleted?
If you change your main to match then the memory will get cleaned up just fine:
1 2 3 4 5 6 7
int main ()
{
Test *t= new Test(2);
cout<< t->geta();
delete(t);
return 0;
}
Line 5 calls the destructor, which deletes the arr array allocated in the constructor. Delete then frees the memory allocated to the t object itself at line 3. Note that in this case there is nothing on the stack because you specifically allocated t on the heap at line 3.