Re: [Dev-C++] Constructor and Destructor
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Hossein H. <ult...@em...> - 2003-07-10 12:46:49
|
Dear Lohit,
> class A{
>
> public:
> A(){
> delete this;
> }
> ~A(){
> cout<<"~A";
> }
>
> f(){
>
> cout<<"HELLO\n";
>
> }
>
> };
>
> int main()
> {
> A *a=new A();//works
This works because A() returns a copy of "*this" inside it. So, in
calling the constructor, when you delete the "*this" pointer, there
isn't any problem as there is no other need to the copy returned by
A(), and it is going to be deleted by the compiler at the same time.
> A b;//crashes why?? how is it any different from above.
But, here, there is a problem, as you are deleting an object that is
deemed to be alive still. This is an auto object, right? So it is to
be destructed by the compiler, and be alive till that destructor is
called. But you are destructing it using "delete this", beforehand.
>
> A *c;
>
> c->f();//works why when I have not allocated any memory for
> this.
This works as compilers (or at least optimiser compilers) have only
one copy of the member functions. In fact, they are shared between all
the instantiations of a class. As the only differences between
different objects of a class are the data members of them. So there is
only one copy of any member function for a given class. Therefore,
A::f() is created and when c->f() is called, in fact, A::f() is
called.
>
> }
Regards,
--Hossein
--
__________________________________________________________
Sign-up for your own FREE Personalized E-mail at Mail.com
http://www.mail.com/?sr=signup
CareerBuilder.com has over 400,000 jobs. Be smarter about your job search
http://corp.mail.com/careers
|