node() method in CCLayer

node() method in CCLayer
0.0 0


For the static node() method below

CCLayer *CCLayer::node()
CCLayer *pRet = new CCLayer();
if (pRet && pRet->init())
return pRet;
return NULL;

It creates a CCLayer instance and do it’s init function. In case there is a subclass of CCLayer, the node() method cannot work as expected because it does not trigger the constructor of the sub-class.

Please also note that the init() method CClayer is not virtual


So there’s a macro to do this job, and it’s shown in HelloWorld


It caused by the difference between objc & c++ language. I have no idea if there’s a better resolution.


Maybe template can help?


I have added LAYER_NODE_FUNC(HelloWorld) into HelloworldScene.h, which exists in templates of all platforms,

class HelloWorld : public cocos2d::CCLayer
    // ...

    // implement the "static node()" method manually


Sorry that my words may be misleading. What I mean is “template” in C++

CCLayer* node()
T* temp = new T();
CClayer* layer = static_cast(T);

something like that. Change the init() method virtual.
Not sure if it works.


Oh, gotcha.
so the calling source should be

CCLayerColor* pLayer = CCLayerColor::node();

A bit ugly… Is there a more elegant approach? The objc code is

CCLayerColor* layer = [CCLayerColor node];

How beautiful it is!

I would like to write it into marco in early versions, it’s more convenience than function template (not increase the binary size), but Ming against this idea.


I agree with Walzer.
I think I prefer macro than template.