cocos2d::Ref* sender

cocos2d::Ref* sender

I’m diving into a large cocos2dx code base. Little documentation and way above my level. I’ve noticed that cocos2d::Ref* pointers are widely used as arguments in methods. What exactly is a cocos2d::Ref* pointer? What is the diference from a normal C++ pointer? Where can I learn more about this?

thanks in advance

It is a normal C++ pointer, so your question is a little strange. What exactly do you mean by it? Perhaps it’s best to brush up on C++ before diving into the Cocos2d-x code.

cocos2d::Ref is just a class, and cocos2d::Ref* is a raw pointer to an object of type cocos2d::Ref.

Find the definition of the cocos2d::Ref class, which would be a ‘go to reference’ or ‘go to declaration’ command in whichever IDE you’re using. You could also just use the search function in the IDE, and you would end up here in CCRef.h, where you would see this comment in the code:

 * Ref is used for reference count management. If a class inherits from Ref,
 * then it is easy to be shared in different places.
 * @js NA
class CC_DLL Ref
... rest of the class which a lot more comments

A quick Google search for what is cocos2d::Ref would have sent you to the docs:

Aside from that, this may help you along (not specifically related to cocos2d::Ref):

Where you see cocos2d::Ref* is most likely in event handlers or callbacks etc. In these cases you would need to cast that Ref pointer to the type you’re expecting, and check that it’s valid (unless you’re 100% certain it is).

For instance:

void ClickHandler(cocos2d::Ref* sender)
    auto button = dynamic_cast<cocos2d::ui::Button*>(sender);
    if (button != nullptr)
        // It's a valid button pointer...

Hello @R101,
Thanks for the answer.
If I understood right, your method ClickHandler expects a pointer of type cocos2d::ui:Button, but, just to be sure, it uses as argument a pointer to the cocos2d:Ref and then checks if the pointer can be casted to a Button.
Did I understood right?
Can I use this strategy (cocos2d:Ref pointers) with any type of cocos2dx class ? … because I thought dynamic casting was mainly used with inherence and cocos2d:ui does not inherits from cocos2d:ref.


That is correct, but the ClickHandler example can also handle clicks for other types of objects as long as they are also sub-classes of Ref. There are a number of valid reasons to have a function accept a reference or pointer to a a base class, which you then typecast to the required sub-class.

I don’t understand what you mean by that? cocos2d::ui is not a class, it’s a namespace. You must be thinking of cocos2d::ui::Widget, which all cocos2d::ui:XYZ objects inherit from. If you follow the inheritance tree, you’ll eventually see that ui::Widget also inherits from cocos2d::Ref. If you are unsure, just check the source code, it’s all there.