Why the pointer style?

Why the pointer style?
0.0 0


Hi everyone!

I’m just getting started, but I notice that cocos2d-x uses a lot of this pointer style

CCSprite* mySprite = CCSprite::spriteWithFile("button.png", CCRectMake(0,35 * 0,300,35));

Then, there’s obviously a lot of -> from then on. From writing C*+ I’m used to something like this:
CCSprite mySprite("button.png", CCRectMake(0,35 * 0,300,35));
Which mySprite on the stack, and it allows you to write mySprite.method() instead of mySprite->method(). How does it work in cocos2d-x: Does spriteWithFile allocate on the stack or on the heap?
Another example:
CCMenu * CCMenu::create(CCMenuItem* item, ...) {/* etc */}
Why is item passed as a pointer? From my knowledge, the preferred C*+ way would be CCMenu::create(CCMenuItem& item, ...) because passing by reference is safer and there’s no pointer arithmetics in the function.

I’m not an expert C++ programmer, can someone please just give me a few hints on why it’s done like this?


Well the one of the reason I believe is that in some cases we want to pass a nullptr in some functions and with a reference we can’t do that. Mixing the two styles would make the API inconsistent. In the case CCMenu::create, we probably want to pass a CCMenuItem and not a nullptr, but let’s say we want a CCMenuItemSprite (or CCMenuItem) and make a button that does nothing (while developing or just for fun) we can do that with pointers. The more IMPORTANT reason why pointers, is that we are allocating and deallocating memory on the go (and stack variables just don’t make sense here), and when working with dynamic memory, (as far as I know) using pointers is the only way.


Okay yeah I can see your point :slight_smile:

With dynamic memory you could use Smart Pointers, but it would mean C++11 or boost as a requirement which of course is a disadvantage. And with games it can become so performance-critical that the overhead over a raw pointer might be an issue.

Thanks for clearing that up!


No problem. Glad it helps. But keep in mind that it’s just my opinion… C*+ 11 has some nice features . this link http://www.cocos2d-x.org/boards/6/topics/18123 introduces some of the C*+ 11 features, one are Smart Pointers that work with cocos2dx.