xxxxxxxxxx
// CPP program to illustrate
// Private Destructor
#include <iostream>
using namespace std;
class Test {
private:
~Test() {}
};
int main() {}
///Works Fine
// CPP program to illustrate
// Private Destructor
#include <iostream>
using namespace std;
class Test {
private:
~Test() {}
};
int main() { Test t; }
///Doesn't work error: ‘Test::~Test()’ is private
// CPP program to illustrate
// Private Destructor
#include <iostream>
using namespace std;
class Test {
private:
~Test() {}
};
int main() { Test* t; }
///Works Fine.There is no object being constructed, the program just creates a pointer of type “Test *”, so nothing is destructed.
// CPP program to illustrate
// Private Destructor
#include <iostream>
using namespace std;
class Test {
private:
~Test() {}
};
int main() { Test* t = new Test; }
///WOrks Fine.When something is created using dynamic memory allocation, it is the programmer’s responsibility to delete it. So compiler doesn’t bother.
#include <bits/stdc++.h>
using namespace std;
class Test {
public:
Test() // Constructor
{
cout << "Constructor called\n";
}
private:
~Test() // Private Destructor
{
cout << "Destructor called\n";
}
};
int main()
{
Test* t = (Test*)malloc(sizeof(Test));
return 0;
}
///Works Fİne BUT The above program also works fine. However, The below program fails in the compilation. When we call delete, destructor is called.
// CPP program to illustrate
// Private Destructor
#include <iostream>
// A class with private destructor
class Test {
private:
~Test() {}
public:
friend void destructTest(Test*);
};
// Only this function can destruct objects of Test
void destructTest(Test* ptr) { delete ptr; }
int main()
{
// create an object
Test* ptr = new Test;
// destruct the object
destructTest(ptr);
return 0;
}
///We noticed in the above programs when a class has a private destructor, only dynamic objects of that class can be created. Following is a way to create classes with private destructors and have a function as a friend of the class. The function can only delete the objects.