Reputation: 964
This question relates to C++ game engine, called AppGameKit (AGK).
I've created a separate class for Text so that I don't have to call AGK functions when creating Text. Here's the simple class:
Text.h
class Text
{
private: int _ID;
void Destory();
public:
void AddText();
Text(int ID);
~Text();
};
Text::Destroy()
{
agk::DeleteText(_ID);
}
Text::~Text()
{
Text::Destroy();
}
Now my question is when I'm calling this class in any other class, say MainMenu, do I have to delete the button in the class MainMenu that I'm creating using this class or will the destructor of Text will automatically get called and delete the button.
MainMenu.cpp
MainMenu::Initilization()
{
Text * mainText = new Text(1);
}
MainMenu::Destory()
{
agk::DeleteText(1); // DO I HAVE TO DO THIS?
}
MainMenu::~MainMenu()
{
MainMenu::Destory();
}
AGK function delete is called to delete text so that the memory is deallocated. Similar to C++ delete keyword.
Personally, I think deleting the button in MainMenu class should be unnecessary but I'm confused as to whether the destructor of Text class is even called. Please let me know if you think I'm wrong.
Upvotes: 2
Views: 1326
Reputation: 30489
Do I have to manually delete object even after destructor?
No.
You called Text * mainText = new Text(1);
in Initialization
, so call delete mainText
in Destroy
When you call delete mainText
mainText
is not null its destructor would be calledmainText
is not null its memory would be freedNo need to mention, the destructor already calls agk::DeleteText
Upvotes: 2
Reputation: 1130
The basic rule of thumb in C++ is for every new() there must be a delete(). This ensures that there would be no memory leakage. In most modern OS, there is no memory leakage ever. Once your program exits, the OS claims back the memory and puts it back in heap. But what happens when your program is running for a long time. This means you will keep leaking memory until your program exits. So it's best to delete the allocated memory and adhere to the rule of thumb.
Hope it helps!!
Upvotes: 1
Reputation: 234685
Every new
has to be balanced with a delete
else you will leak memory. (You can use classes like std::unique_ptr
which will manage the deletion for you but they still call delete
under the hood).
Currently, mainText
goes out of scope at the end of the Initilization
function, so you lose the pointer that you need for a successful delete
.
Upvotes: 3