0

I am making a Bubble Pop game in C++ where the user clicks on randomly generated Bubbles that float up the screen(still very much in development). In order to Use OpenGl and Glut with this game I found that it was best to make my Bubbles global. I have a blank destructor but I do not know how to delete the contents of the Bubble and create a new one. I tried using dynamic allocation but it didn't make a difference. How can I delete the contents of the Bubble and make a new one?

Here's a necessary snippet: main.cpp

Bubble myBubble1; void display(void) {
delete myBubble1;//error "cannot delete type Bubble" 
}

My destructor is here:

class Bubble { 
  public:
 //default constructor

 Bubble()
 {

     radius=(rand() % 100 )+1;
     speed = rand() % 500 ;
     xVal = rand() % 480;
     yVal= -14;
     isLive=true;

 }
 ~Bubble()
 {

 } 
private:

 float radius;
 float speed;
 float xVal;
 float yVal;
 bool isLive;
};

The code runs fine when I don't try to delete anything. I can run infinite looping bubbles

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
  • As a way to help remember: Any time you use `new`, you should have a corresponding `delete`. If you never use `new`, you have nothing to delete *manually*. See questions like http://stackoverflow.com/q/716353/1751715 and it's duplicate for more info. N.B. ~ Every delete must be on it's own `delete thingy;` line. You can't write `delete thing1, thing2, thing3;`; see http://stackoverflow.com/q/3037655/1751715. – Hydronium May 02 '13 at 12:14

2 Answers2

0

You are not using any pointers in your Bubble so your destructor can stay blank. If you want to reassign your Bubble just so

Bubble myBubble1;
//use myBubble1
...
myBubble1 = Bubble();
bash.d
  • 12,357
  • 2
  • 24
  • 37
0

If you're declaring a Bubble in a scope like this:

void func()
{
    Bubble b;
}

It will be destroyed immediately after you exit func()'s scope. (RAII)

The only time you need to use delete is when you're allocating memory for a Bubble manually and you can only do this to a pointer:

void func()
{
    Bubble* b = new Bubble;

    delete b;
}

If you want to delete it at will, declare it as a pointer (a smart pointer like std::unique_ptr is preferred) and delete at will. (Or smartPointer.reset())

user123
  • 8,613
  • 2
  • 25
  • 50