Events: Why override AND register?

Hello,

I have a simple technical question: In all the tutorials I have read the touch handling was always 2 step process:

  1. Override the virtual methods like onTouchBegan in your layer sub class:

     virtual bool onTouchBegan(cocos2d::Touch*, cocos2d::Event*); // In header
    
  2. Register the overriden methods:

    touchListener->onTouchBegan = CC_CALLBACK_2(HelloWorld::onTouchBegan, this);

To be honest this is really strange to me as a C++ developer. To me either approach (overriding OR method registration) would be sufficient to plug in my custom code. Why do I need to override AND register the overriden method into the cocos system?

Thanks!

The virtual methods on Layer is something from older engine that exists for backward compatibility. It’s effectively deprecated going forward, as I understand it.

The event listener is the newer system that allows getting touch events for any node, not just a layer. Also the callbacks can be supplied with any function that matches the signature below. This also allows you to use a lambda if you want to supply the concrete event method in-place within your code. This also means you could add a non-virtual method of any name that doesn’t already exist in your class or any of its base class’ virtual methods.

std::function<bool(Touch*, Event*)>

See the programmer guide for more info:
http://cocos2d-x.org/programmersguide/8/index.html

Maybe those tutorials are wrong. Can you provide a link?
There was never a two-step process, but only two different systems.

You don’t have to. There are just two types of implementations available.

This is because of compatbility reasons. In 2.x you needed to override the function, which acts as a delegate.

3.x has a new event dispatcher system, which can register a callback/delegate.