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
You are asking about a particular style of syntax more than a language limitation. C++ allows you to call an object's constructor or destructor.
c objC;
objC.~c(); // force objC's destructor to run
new(&objC); // force objC's constructor to run
Why did the language designers not use this syntax instead?
c objC;
delete(&objC) c; // force objC's destructor to run
new(&objC) c; // force objC's constructor to run
Or why not:
c objC
objC.~c(); // force objC's destructor to run
objC.c(); // force objC's constructor to run
My opinion as to why they chose the syntax they did: The first alternative is more flexible than the second. I can call the constructor / destructor on any address not just an instance. That flexibility is needed for allocation, but not for destruction. Also the first option's delete seems to be very dangerous once virtual destructors get in to the mess.
you can invoke the constructor of an instance's class using typeof
:
class c
{
public:
void add() ;
c();
~c() ;
};
void main()
{
c objC ;
objC.add() ;
objC.~c() ; // this line compiles (but is a bad idea)
typeof objC otherObjC; // so does this.
}
This does not affect the value of the instance objC
, but creates a new instance otherObjC
using objC
's class constructor.
Note: this may do something you don't expect if the static type is a baseclass of the dynamic type of the instance you have.
The constructor is there "c()" used with new, i.e.
c objC = new c();
If you want to call your constructor outside of the actual construction of the class instance then you either haven't understood the purpose of the constructor or are trying to put functionality in there that shouldn't be there.
A destructor must be called on an existing instance of a class - destructing the instance is what it does. A constructor creates a brand new instance of a class, so calling on an existing instance makes no sense.
This is similar to the way new and delete work:
int * p = new int; // call to new needs no existing instance
delete p; // call to delete requires existing instance
And note in your code, the object would be destroyed twice, once explicitly, and once implicitly at the end of its enclosing scope. You typically only explicitly call a destructor if you are doing something unusual, probably involving the use of placement new.