views:

107

answers:

4

I'm not very familiar with C++ programming. I know the basics of programming in it (syntax, pointers, etc.) and I've built a few basic programs with it and done some basic debugging at work. I am puzzled by this line of code from Box2D, specifically the Box2dTest project from Cocos2D:

// Define the ground body.
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0, 0); // bottom-left corner

How is it that one can do this without having initialized groundBodyDef? I know this isn't an Objective-C thing because the C++ examples for Box2D itself are just like this.

+2  A: 

The object has been initialized by its constructor on the first line.

I would recommend the following link, which is a very good text on C++: The C++ Annotations.

RedGlyph
I'll read that thanks! I'm coming from Java and C#, where the convention for initialization is: `MyObject foo = new MyObject();`
jasonh
That's right, in C# those objects are always treated as reference, which is only the case in C++ when using pointers. In general, you have to control the life of your objects in C++ whereas it is done automatically in C#. You will find a good overview of the difference between both languages here: media.wiley.com/assets/264/22/0764557599_bonus_AppD.pdf
RedGlyph
+7  A: 

groundBodyDef actually is initialized!

I think you expected something along the lines of:

b2BodyDef *groundBodyDef = new b2BodyDef();

which is actually still valid, but it is initialized on the heap. In your version, groundBodyDef is initialized on the stack, much like you would initialize an int on the stack.

As it is called without parameters, the default constructor is used.

Chaosteil
Yep, that's exactly what I was expecting. I typically program in C# and sometimes Java.
jasonh
+1  A: 

If you do classname variable; then variable will be initalized by calling the default constructor of classname, meaning there is no unitialized variable in your code.

sepp2k
+2  A: 

If b2BodyDef has a decent default constructor, then the part about "without having initialized" just doesn't apply -- the default ctor HAS initialized groundBodyDef!

Alex Martelli