Newbie: Delete CCLabelTTF created in main from inside of a function?

Hi. This is probably a very basic question, but I am getting stuck for whatever reason, and I would appreciate your help.

I created this button as part of a menu.

auto mButton = MenuItemFont::create(buttonLabel, CC_CALLBACK_0(SecondScene::Buttonpress, this));
auto menu = Menu::create(back, okay, mButton, main, NULL);

void SecondScene::Buttonpress()
{
//delete mButton
}

I want mButton to be deleted when SecondScene::Buttonpress is called, but I don’t know how to include it in the scope of the function using CC_Callback. Could anyone provide me with a brief explanation of how to do this?

Why don’t you create mButton in the header, then you can access it from every function in the .cpp?

Just to clear things up a little bit here. You shouldn’t create mButton in the header.
But you could however define a pointer to the button in private or protected in your scene’s class definition.

For example like this:
in SecondScene.h

class SecondScene : public cocos2d::Layer
{
protected:
	cocos2d::MenuItemFont* _mButton {nullptr};

Then you create your button and menu as usual in the function body of your choice, for example in bool SecondScene::init()

	_mButton  = MenuItemFont::create(buttonLabel, CC_CALLBACK_0(SecondScene::Buttonpress, this));
	auto menu = Menu::create(back, okay, _mButton, main, nullptr);

And void SecondScene::Buttonpress() could look like this:

void SecondScene::Buttonpress()
{
	_mButton->removeFromParent();
	_mButton = nullptr;
}

BUT: Far more elegant would be to use a lambda function:
Forget defining the pointer in the header, delete you Buttonpress method.
Just create your menu like this:

auto mButton  = MenuItemFont::create(buttonLabel, [](Ref *sender){
	static_cast<Node*>(sender)->removeFromParent();
});
auto menu = Menu::create(back, okay, mButton, main, nullptr);
```

BTW: I'm assuming `buttonLabel` is a std::string. Isn't it a little bit confusing to call a `string` a `Label` ;-)

Your pointer method worked for me, and I really should have thought of that myself. I’ll do some research about the second solution. Also, yes, it is a std::String :slight_smile: I guess it is pretty confusing.