Difference between subclassing a Node and a Sprite?

Hi!

Can somebody tell me what the difference between subclassing a Node and a Sprite? I mean the only thing I have noticed is that you can do more when you subclass Sprite but of course - there is a reason why I ask :smile:

Thanks!

hmm i think you can check the API document ?

I have but it did not really explain what pros and cons there are when subclassing from those and when really to use what

Sprite is a subclass of Node, so any class you create that subclasses Sprite will get all the functions and variables of a Node as well. So, Sprite takes Node and adds variables and functions for handling an image, because a Sprite object and any subclass of Sprite is supposed to be an image.

If the object you want to create is an image, subclass Sprite. If it is not an image, subclass Node. It is less efficient to subclass Sprite if your object is not an image.

Okay thank you so much! But why do even want to derive the class from Node - What does it make you able to do?
And you seem to know a lot so I will just ask you right away :smile::
When I see people make classes and derive them from nodes they are always using new when initializing them but why not just ClassName::create()?
Thank you!

You can always derive from cocos2d::Ref*, you can think of this as the base cocos2d-x class. It replaces CCObject from v2.

1 Like

I believe a Node is the most basic object you can add to a scene and all other objects you add to the scene will be subclassed from it, e.g. Layer, Sprite, Label.

One reason you might use a Node is if your object is something you can’t see, but does something to the children added to it. For example, if you want to move multiple Sprite objects at the same time, if they are all children of the same Node, you could move that Node instead of moving each Sprite individually.

I am not sure why people would use new. Maybe they add the functionality of the create function to their class’s constructor. I use the create function myself.

1 Like

Sprite objects are already a node object in the scenegraph. If you need to reimplement a sprite properties, you may use the sprite inheritance. If you just want to reimplement node properties, you may use the node inheritance.

1 Like

I think, “ClassName::create()” method is using because of the creational design pattern in the engine architect. Actually cocos2d-x uses the singleton and creational patterns.

https://en.wikibooks.org/wiki/C%2B%2B_Programming/Code/Design_Patterns/Creational_Patterns

1 Like