While I see a plethora of Stack Overflow Questions and Answers for virtual functions calling their sub/superclass functions of similar name, I'm getting this:
CCLog("Yay"); //ensure it's called
CCScene * tScene = TitleDescription::scene(); //grab the scene
TitleDescription * t = reinterpret_cast<TitleDescription *>(tScene); //Unsure why this even works when I think about it, a scene is returned but the below call:
t->loadWithDataFrom("Information.xml", "story"); //calls setScaleX on CCObject instead.
CCDirector::sharedDirector()->replaceScene(tScene ); //runs with an empty scene on one condition
The condition that the scene loads with loadWithData is that I make the function void name(types). I followed cocos2d-x's pattern and used virtual, and in that case, it calls setScaleX instead, I used the debugger and stepped into it.
I have two questions.
1) If the scene() function returns a scene (with a child node of the TitleDescription type), then how is this call even functioning (when nonvirtual and running as I want, eg: calling the right function) ?
2) When it messes up, is the vTable just pointing to a garbage location, that happens to always be the same function?
Note: In cocos2d (and X), scenes are subclasses of layers, which subclass CCObject. CCObject does containe the function that gets called, but the name and parameters differ a lot, and I'm not getting why a function, whose name and params will be completely different, gets called.
I'm open to any references and good documentation on this. I'm suspicious that my cast (set to reinterpret just to force-bypass everything), is possibly why the virtual function is pointing to the same function every run, including when I change the signature to bool instead of void, and clean the build.
Note: XCode is the environment I'm in. I don't believe it's using LLVM yet either. I will try tweaking that and seeing what happens.
Like everyone else, I don't think I fully understand vFunctions, even though I'm aware of the use of abstract classes and forced overriding. (Being the first class with that func, I don't see why it needs to be virtual at this time, but I do plan on extending the function in subclasses due to what I'm doing).
Thanks, Steve J
reinterpret_cast
will not downcast correctly. Remember that the base subobject may not be at the beginning of the complete object.
Use implicit conversion for upcasts, and static_cast
or dynamic_cast
for downcasts, and dynamic_cast
for crosscasts. They will include the appropriate offset when needed and not just return the same address the way reinterpret_cast
does.
And none of these will get you between a parent and member (non-base) subobject.
Avoiding casts altogether is by far the best.