init method not being called in custom CCLayer class

Hello world! First off, I wanted to comment on what a great community you all have here! I’ve been lurking on these forums for a few months now and your posts have all been very helpful in my learning process.

I’m trying to create a custom CCLayer class. In this class, I would like to handle a ccTouchesEnded action event. However, the init method is not being called. I believe I may have created my class incorrectly, but I do not know the exact reason.

TargetLayer.h

class TargetLayer : public cocos2d::CCLayer
{
public:

  virtual bool init();

  static cocos2d::CCLayer* layer();

  void ccTouchesEnded(cocos2d::CCSet* touches, cocos2d::CCEvent* event);
};

TargetLayer.cpp

CCLayer* TargetLayer::layer()
{
  CCLayer * layer = NULL;
  do 
  {
    // 'layer' is an autorelease object
    layer = CCLayer::node();
    CC_BREAK_IF(! layer);
  } while (0);

  // return the layer
  return layer;
}

bool TargetLayer::init()
{
  bool bRet = false;
  do 
  {
    CC_BREAK_IF(! CCLayer::init());

    CCSize screenSize = CCDirector::sharedDirector()->getWinSize();

    this->setIsTouchEnabled(true);

    bRet = true;

  } while (0);

  return bRet;
}

GameScene.cpp

  CCLayer* targetLayer = TargetLayer::layer();
  targetLayer->init();
  this->addChild(targetLayer);

Thanks for taking the time to read this! Any advice would be greatly appreciated! :slight_smile:

The keyword “self” in objc can automatically point to children class at runtime, while keyword “this” in c++ cannot.
So you need to use LAYER_NODE_FUNC marco in your TargetLayer declaration like

class TargetLayer : public cocos2d::CCLayer
{
public:

  virtual bool init();

  static cocos2d::CCLayer* layer();

  void ccTouchesEnded(cocos2d::CCSet* touches, cocos2d::CCEvent* event);

  LAYER_NODE_FUNC(TargetLayer); // HERE!
};

Then call layer = CCTargetLayer::node(); instead of CCLayer::node() in TargetLayer::layer() method. You can read the code in LAYER_NODE_FUNC marco for more details.

Thank you Walzer!

Your advice to use the macro and then call the node() method of the custom class worked! I’ve come across many of your posts on this forum, you are always knowledgeable and helpful!