Is there a way to call constructor with class instance pointer?
No. You cannot.
Con* c = new Con( 1 );
//c->Con( 2 ); //illegal
You've already called the constructor in the new
expression.
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?
You can only call the constructor when the object is being constructed, hence it's name. Once the object is constructed, I see no reason why you'd want to call it again on the same object. If you want to do something then, you need to call a function defined in that class.
You can actually call it, it is just that the syntax is not that of calling a member method (of which the destructor is an special case), so it is not done with the member access operators. Rather you have to resort to the placement-new syntax:
Con c;
c.~Con(); // destroy, now c is not a Con anymore
new (&c) Con(); // recreate, now c is a Con again
As a particular case, in the C++0x proposal, that is actually used in one of the code examples, providing means to reuse a union
as a different type in the event of an union containing non-POD elements:
union U {
int i;
float f;
std::string s;
};
int main() {
U u;
new (&u.s) std::string( "foo" );
u.s.~string();
u.i = 5;
}
}
It will be easier for you if you don't think of constructor and destructor as a functions, that you call. You don't call them. You can only construct or destruct an object. And, as a part of constructing, constructor body is executed. Same, as a part of object destruction, destructor body is executed.
So you can construct object on the stack
YourClass variable(constructor_arguments);
and it will be destructed automatically when it's out of scope.
You can also create object on the heap
YourClass * ptr = new YourClass(parameters);
To destruct such an object you use operator delete
delete ptr;
You can also construct an object in some memory you provided by yourself (rarely needed)
char * pool = new char[sizeof(YourClass)]
YourClass *ptr = new(pool) YourClass(parameters);
You destruct such an object explicitely and the syntax looks like function invokation, but it's rather an object destruction
ptr->~YourClass();
After this line your object is no more. Invoking anything on it is an undefined behavior. And you still have to manage the memory you allocated for this object
delete[] pool;
So, your question means 'Why can I explicitely destruct an object to which I have a pointer but I can't construct it'? You can't, because it is already constructed.
You can also read C++ FAQ Lite explanation