When can an object of a class call the destructor of that class, as if it\'s a regular function? Why can\'t it call the constructor of the same class, as one of its regular
I think you can explicitly call the destructor if you make sure that the instance is replaced/recreated with a call to placement new:
class c
{
public:
void add() ;
c();
~c() ;
};
int main()
{
c objC ;
objC.add() ;
objC.~c() ; // this line compiles
new (&objC) c; // placement new invokes constructor for the given memory region
}
I've never seen this in practice, but logically it should work (unless c's constructor can throw, in which case, I imagine, hell could break loose during stack unwinding).
However, what you probably want is just assignment:
objC = c();
If the destructor has side-effects that you are interested in, implement assignment using the copy-and-swap idiom which gets the destructor invoked for the "left-hand" value.