[comp.lang.c++] an object killing itself.

helz@gorilla.ecn.purdue.edu (Randall A Helzerman) (06/09/91)

Hey net.c++.wisepersons...
I have an application where it would be very convenient for a member
function to be able to do the equivelent of deleting the object it is
a member of, as shown in the following code:

-------cut-here------------------------------------------

#include <stdio.h>

class depressed{
    int i;
 public:
    hara_kiri(){
	printf("Goodbye Cruel World....BANG!!!\n");
	delete this;
	printf("thunk!\n");
    }
};

depressed *b;

main(){
    b=new depressed;
    b->hara_kiri();
    printf("Back in the main program.\n");
}

----cut-here------------------------------------------

Is this OK?  I never reference any data from the object again--I
simple want the return from the member function hara_kiri() to go as
planned.  Would it still be OK if hara_kiri(), instead of deleting the
object itself, called another function which deleted the object?

Thanks in advance for wadeing through the code.

cadsi@ccad.uiowa.edu (CADSI) (06/10/91)

From article <1991Jun9.080138.2540@noose.ecn.purdue.edu>, by helz@gorilla.ecn.purdue.edu (Randall A Helzerman):
> Hey net.c++.wisepersons...
> I have an application where it would be very convenient for a member
> function to be able to do the equivelent of deleting the object it is
> a member of, as shown in the following code:
> 

[ stuff deleted ]

I use the WM_DESTROY messate in Windows code to do JUST this.  It
has worked for me (Borland C++) with no hitches.

class classofstuff {
	member1 { do_some_stuff() ;  delete this }
	.
	.
}

[source and other stuff deleted]

|----------------------------------------------------------------------------|
|Tom Hite					|  The views expressed by me |
|Manager, Product development			|  are mine, not necessarily |
|CADSI (Computer Aided Design Software Inc.	|  the views of CADSI.       |
|----------------------------------------------------------------------------|