I want to explicitly call the destructor of an object in C++ to destroy that object.
This is just a simple program to experiment with the features of the programming languages. I have a default constructor which sets the internal data member to 1, and overloaded constructor which sets the internal data member to the parameter, and a destructor which displays the internal data member of the just destroyed object. There is also a function which prints the internal data member.
#include <iostream>
using std::cout;
using std::endl;
class myClass {
public:
myClass()
{
i = 1;
cout << "default ";
cout << "constructor called with " << this->i << endl;
}
myClass(int i)
{
this->i = i;
cout << "constructor called with " << this->i << endl;
}
~myClass()
{
cout << "object " << i << " destroyed!" << endl;
}
void printData()
{
cout << "object's data is " << i << endl;
}
private:
int i; // private data member
};
int main() {
myClass a;
myClass b;
myClass c(8);
a.printData();
b.printData();
c.printData();
/* I want to explicitly destroy object b. */
b.~myClass();
b.printData();
/* all the destructors get called when the objects go out of scope */
return 0;
}
My reasoning is this: I think that the destructor causes the object to be destroyed, so it no longer exists in the memory. After I explicitly call the destructor, I should be no longer able to use that object again, since it is destroyed. However, I am able to call a function of the object and print the value of the internal data member. Did manually calling the destructor fail to destroy the object? What's going on here? Output:
default constructor called with 1
default constructor called with 1
constructor called with 8
object's data is 1
object's data is 1
object's data is 8
object 1 destroyed!
object's data is 1
object 8 destroyed!
object 1 destroyed!
object 1 destroyed!
Does calling the destructor destroy the object, or is calling the destructor a RESULT OF destroying the object?