0

My program crashes upon exit. Tracing the error back I arrived at the destructor of the class gWSW. Here is the problem:

I have a class gShop: public gTexture. In this class I declare and initializes a pointer to an object of the class gWSW.

In gWSW I have again a pointer to an object declared and initialized of the class gTexture.

I have given every class the proper destructor with calling delete on the pointers.

The programm runs fine until I press ESC and all the desctuctors are called. Here it crashes in the destructor of gWSW. That is I have something like that:

class gShop : public gTexture
   {
   public:
       gShop(): pWSW(new gWSW()) {}
      ~gShop(){delete pWSW;}   

   gWSW*    pWSW;
   };

class gWSW 
   {
   public:
       gWSW():gWSW: pTextuer(new gTexture()) {}
      ~gWSW(){delete pTexture;}   

   gTexture*    pTexture;
   };

class gTexture 
   {
   public:
       gTexture() {}
      ~gTexture();

//... a pointer to char[] here but will be also deleted in its destructor
   };

The last call before crashing is in ~gWSW(). Commenting "delete pTexture" out makes the program exit fine without errors or crashes. Before I continue and leaving it commented, I like to understand what the problem is please.

CodeTrek
  • 435
  • 1
  • 3
  • 10
  • 1
    http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three – Chad Oct 12 '13 at 02:26
  • 4
    You'll need to write defensive code. Make the copy constructor and assignment operator private so you can never accidentally copy the pointer. If you now get a compile error then you've found the cause. – Hans Passant Oct 12 '13 at 02:28
  • Shall I have to do a deep copy of all pointers involved by including it in the copy constructor? *ptr = object.ptr? It's been a while but I start to remember that has to be done. Thanks – CodeTrek Oct 12 '13 at 02:47

1 Answers1

0

Ohh I believe I found the answer. It had been a while since I visited the "stack". I need to make an own copy constructor and thus provide a deep copy of every object.

In this way memory is allocated from the heap to a new pointer. The value at the new memory location is assigned the values from the original object.

Special thanks to Hans Passant that advised me to find the error by always making the copy constructor private.

CodeTrek
  • 435
  • 1
  • 3
  • 10