We can call destructor explicitly through class pointer, why not constructor? Any idea?
#include <iostream>
class Con {
public:
Con( int x ) : x( x ) {
}
private:
int x;
};
int main() {
Con* c = new Con( 1 );
//c->Con( 2 ); //illegal
c->~Con(); // ok!
delete c;
}
Thanks,
No. You cannot.
You’ve already called the constructor in the
newexpression.By the time you’ve a valid pointer of type
Con*, you’ve already created an object. And calling constructor on the “constructed” object doesn’t even make sense. So why would C++ allow that?