Official Forum for Programming in Objective-C (the iPhone Programming Language) - Stephen Kochan
June 21, 2018, 08:38:32 PM *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
 
   Home   Help Search Login Register Chat  
Pages: [1]   Go Down
  Print  
Author Topic: Is calling init on a new object optional?  (Read 3537 times)
SgtLex
Newbie
*
Posts: 2


« on: April 28, 2014, 08:46:09 AM »

I come from a C# background where we don't have to explicitly allocate memory for and initiate our objects (I guess we do, but it's all wrapped up in calling new MyObject()). Anyway, I was playing around with the code for creating a Fraction object and I found that these are equivalent:

Code: (Objective-C)
Fraction *myFraction;
myFraction = [Fraction alloc];
myFraction = [myFraction init];
[myFraction print];

Output is: 0/0

Code: (Objective-C)
Fraction *myFraction;
myFraction = [Fraction alloc];
[myFraction print];

Output is: 0/0

Is this just because Fraction is such a simple object that calling init is not necessary? I know this is poor programming practice, I'm just trying to get a handle on why this works without calling init. I would have expected the second bit of code to throw some type of exception related to an uninitialized object.
Logged
BrianLawson
Sr. Member
****
Posts: 262


Email
« Reply #1 on: April 28, 2014, 10:42:06 AM »

You can use an object which has been allocated but not initialized but the results will be unpredictable. It was a happy coincidence that your un-inited fraction had zeros in it.
Logged
SgtLex
Newbie
*
Posts: 2


« Reply #2 on: April 28, 2014, 07:23:59 PM »

Thanks, that's sort of what I was thinking and I appreciate the answer.
Logged
Pages: [1]   Go Up
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!
Entire forum contents ゥ 2009 classroomM.com. All rights reserved.