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 */
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:
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.