When are objects deleted? Impact of creating objects c++

2k Views Asked by At

I am helping program a game in c++ for the Nintendo DS (It has about 3MB of RAM). For all the menus in the interface, a "button" used to be created by calling void function that sets the background tiles to a button. There are at least 30 buttons throughout the interface. Now I've created a button class that stored its position, label, along with other data values. Now my question is:

Will all these new button objects affect the RAM usage (Or other performance aspects) after the program leaves the object's scope?

Or will the object automatically be discarded once the program leaves the function it was created in?

Here is some code:

#include "Button.h"

void titlescreen() //Called to create main menu
{
    Button singlePlayer = Button(4, 5, "Single Player");
    //Creates button at coord (4,5)

    Button multiPlayer = Button(4, 8, "Multi Player");
    bool chosen = false; //Whether an option has been clicked

    while(!chosen)
    {
        //Menu stuff here
    }
}

Button.h:

#include <stdio.h>
#ifndef BUTTON_H
#define BUTTON_H

class Button
{
public:
    int length;
    int x, y;
    bool isColored;
    void setColored(bool);
    void setDefault();
    button(int, int, const char * const); //Constructor
    button(int, int, const char * const, int); //Constructor
};


#endif  /* BUTTON_H */
2

There are 2 best solutions below

3
On BEST ANSWER

Though your terminology is lacking, the code you wrote allocates the objects "on the stack", and so only last as long as your scope.

In fact, you can write it even more concisely:

//Button singlePlayer = Button(4, 5, "Single Player");  // bad, uses the copy constructor
Button singlePlayer(4, 5, "Single Player");             // uses just a constructor call

Anyway an important thing you should be aware of is that since you're using the "stack" to hold your objects, whether or not you're "allocating" or "freeing" them your "RAM usage" will not change. The "stack" in most implementations is a pre-allocated chunk of memory that never expands, it just throws stack overflow exceptions (or your framework equivalent, I think C has a signal for it?) when it fills up. So generally using your "stack" up on objects is a bad idea.

1
On

Yes, objects are destroyed when they go out of scope (i.e. the destructor of the Buttons are called). So singlePlayer and multiPlayer will be destroyed when program returns from the function titlescreen.

So, as long as the destructor of Button cleans up everything, the buttons won't affect the RAM usage after the function returns.

Also, you should include the C++ header file cstdio instead of the c-header stdio.h.