Search code examples
c++cocos2d-xcocos2d-x-3.0

Cocos2d-x V3 How to override ::create() properly?


I have Player class defined like this:

"Player.h"

#ifndef PLAYER_h
#define PLAYER_h

#include "cocos2d.h"

USING_NS_CC;

class Player: public Sprite {
public:
     Player();
     ~Player();


private:
    Sprite *playerSprite;

    __String name;

    int maxHP;
    int currHP;

    int maxMP;
    int currMP;

    int maxEXP;
    int currEXP;
 };

#endif

and "Player.cpp":

#include "Player.h"

I want to initialize int maxHP, int maxMP .. etc upon

Player* myPlayer = Player::create();

What would be the proper way to override ::create() function with parameters such that

// create(int maxHP, int currHP, int maxMP, int currMP, int maxEXP, int currEXP)
Player* myPlayer = Player::create(100, 100, 100, 100, 100, 100); 

can be used?


Solution

  • You can overload create (have multiple functions with the same name but different signature).

    class Player : public Sprite {
    public:
        static Player* create(int maxHP, int currHP, int maxMP, int currMP, int maxEXP, int currEXP) {
            Player* p = Player::create();
            p->maxHP = maxHP;
            // etc ...
            return p;
        }
    }