Can anyone explain me why do we need to use CREATE_FUNC in Cocos2dx? I saw it in the HelloWorld samples and don't understand it clearly. Please, tell me more detail. Thanks.
We don't need to use it, it is a helper macro which expands to this :
/**
* define a create function for a specific type, such as CCLayer
* @__TYPE__ class type to add create(), such as CCLayer
*/
#define CREATE_FUNC(__TYPE__)
static __TYPE__* create()
{
__TYPE__ *pRet = new(std::nothrow) __TYPE__();
if (pRet && pRet->init())
{
pRet->autorelease();
return pRet;
}
else
{
delete pRet;
pRet = NULL;
return NULL;
}
}
It basically "writes" the create()
method for your type, and calls your init()
implementation. Its main purpose is to call the autorelease()
method, so that you wan't forget about it, if you were to write your own create()
. It may not seem as much, but it takes a little of you.
Tip : in most IDEs you can Control + Click
(Command on MAC) on pieces of code like functions and macros, and the IDE will take you to it.
Let me know if something is still not clear.
EDIT : Question from comment : For specific, if I want to write a CCCarSprite which extends from CCSprite and have some more functions like run, crash...Do I need to call CREATE_FUNCTION(CCCarSprite)?
No, you don't. What you HAVE to do is call one of superclasses init…
methods. This would be best done from your constructor or from your init()
in the subclass.
EDIT 2:
Second question from comment : Just one more, in the HelloWorld sample in Cocos2dx, why do they need to call CREATE_FUNCTION manually?
The don't need to, but it may be considered "good practice" when working with cocos to use their macros, because when they cange something in the create()
function implemented by the macro in new version they only need to update it in one place - the macro definition. This leaves less room for error, as there is virtually no chance to "forget" about a place to change the code to new version.
The more compelling reason to define CREATE_FUNC macro in your function(apart from the memory management) is that, without declaring this, your init() method will never be called.( Check out this piece of code in the macro expansion => if (pRet && pRet->init()))
So this is actually much more than memory management. You can try to put logs in your init method and actually check to verify this.
CREAT_FUNC(ClassName)
just a macro that help us shorty out code.
It contains default ClassName *create()
and bool init()
functions.
After done that, you should implement bool ClassName::init()
on your ClassName.cpp
file.
You could show the details of definition, then you'll find out. Hope that'll help.
© 2022 - 2024 — McMap. All rights reserved.