tags:

views:

98

answers:

3

In an interface such as this:

@interface MyClass : NSObject
{
    bool PlainOldBool;
}

@end

... does PlainOldBool get auto-initialized to false, or is it necessary to use an init method to do that explicitly?

A: 

Objective-C uses the same rules as C for primitive type auto-initialization. In this case, yes, it would be initialized to false.

Marc W
C does not do any kind of auto-initialization. On some OSs (like Mac OS X) the memory pager will return you 0-ed out memory the first time you allocate a page, but if you are reusing memory in your heap, you will definitely get non-zeroed memory eventually. You will also often get garbage in stack variables. In C you must initialize variable specifically in order to get any "default" value or for heap variables, you must call calloc instead of malloc to guarantee the requested memory region is zeroed out.
Jason Coco
C does initialize static variables automatically, but Jason is correct with regard to this context: if you create a struct in C on the heap or stack, it is not auto-initialized.
Stabledog
@Stabledog - Good point, I assumed the context was heap allocations based on the question and just extended to automatic variables. C99 does indeed require static-scoped variables be initialized to the appropriate 0 value.
Jason Coco
+7  A: 

Yes (unless your false is not 0). The default +allocWithZone: method will automatically zero out all ivars.

From http://developer.apple.com/iPhone/library/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW54:

  • It initializes all other instance variables to zero (or to the equivalent type for zero, such as nil, NULL, and 0.0).
KennyTM
Excellent! And thanks for the link.
Stabledog
+1  A: 

Also worth noting is that if you're doing Objective-C++, C++ objects that are ivars of Objective-C objects are not initalized : their constructors are not called by default.

nico_nico
Oh, that's pretty important to know! So what do you do, a bunch of placement new() operators?
Stabledog
Actually I was wrong: by default, the constructors are called. There is a build setting to control that, it's objc-call-cxx-cdtors. If you leave it checked, the "default" ctors (e.g. the ones with no argument) will be called.More details on the gcc manual :http://gcc.gnu.org/onlinedocs/gcc/Objective_002dC-and-Objective_002dC_002b_002b-Dialect-Options.html(Or you can use pointers and call new() manually)
nico_nico