Inheriting from a Cocos2D class and static initializer question

Inheriting from a Cocos2D class and static initializer question
0.0 0


If I have a class that inherits from CCLayer like:

class FieldLayer : public cocos2d::CCLayer

Do I want to override the create() method in this class? Or do I call it like:

FieldLayer* f = cocos2d::CCLayer::create();

if I do that should I override the init() method in my class?


Yes, you should override create method if you want to receive the FieldLayer instead of CCLayer.
Overriding init() method depends from yours needs: if you don’t have to set initial values for some specific data in your class, than you don’t have to override init().


Hi Arthur,

Just to be clear, I should override create() if I want to do things like setPosition(), size, tag, etc.

Then override init() if I want to put things on the CCLayer I just did the create() on like a CCMenu, etc?


You need to override init but I suggest implementign the create method yourself.

class SubLayer : public cocos2d::CCLayer {
    static SubLayer * create();
    virtual bool init();

SubLayer * SubLayer::create() {
    SubLayer * obj = new SubLayer();
    if ( obj && obj -> init() ) {
        obj -> autorelease();
        return obj;
    } else {
        CC_SAFE_DELETE( obj );
        return NULL;

bool SubLayer::init() {
    bool ret = false;

    if ( CCLayer::init() ) {
        // Do init stuff...

        ret = true;

    return ret;



Thanks for this, very helpful. I am basically doing this already just not calling in create() and init() but rather createLayer() and initOptions()