advertisement

Article:
  The Objective-C Language
Subject:   + initialize and - init /not/ compared to constructors in C++
Date:   2001-05-06 16:55:40
From:   halliday
Response to: + initialize compared to constructors in C++

Neither the + initialize class method (spoken of as a replacement
example to the + alloc class method, since it's more likely to
be implemented by a programmer), nor the - init method
(referred to by the articles author as being like a constructor) are much
like C++'s constructors.

C++'s constructors are b*st*rd (I mean it in the non Vulgar Slang senses
of the word) combinations of allocation (implicit in C++'s constructors)
and initialization (what all the code actually contained in the constructor
is supposed to be doing:  And since, at the time the constructor
is called, an instance of the object isn't fully defined, dire consequences
can intermittently befall the programmer that tried to do otherwise). 
The existence of constructors in C++ has more to do with the fact that
instances are created using a "know nothing, third party" new
operator than to any inherent desirability (yes, I do know about stack
allocated instances, but even that can be done in a more accessible method
if C++ had any true concept of a class object and class methods,
but I digress).  (Incidentally, Objective-C used to provide something
sort of similar with + new class methods [except allocation and
initialization were still explicit, allowing the programmer maximal control],
and, yes, these were the methods used to create stack allocated instances
for those language versions that supported them, but this practice is now
deprecated [it provides no new functionality].)

Incidentally, the mention of - init methods being anything
like constructors is the sole problem I have with the article. 
Well, that and the related problem that suggests that it's - init
that defaults to initializing all unmentioned instance variables to zero: 
This is actually done by the way the memory is allocated in the
+
alloc
method (once the + alloc method exits one has a fully
functional instance of the class, with all instance variable initialized
to zero or null or nil, as the case may be [well, actually,
there is the case of the, essentially, hidden instance variable called
isa,
but suffice it to say it's appropriately initialized as well]).  One
never has to deal with partially existent instances, as C++'s constructors
do.


1 to 1 of 1
  1. Michael Beam photo + initialize and - init /not/ compared to constructors in C++
    2001-05-07 10:45:12  Michael Beam | O'Reilly Author [View]

    • + initialize and - init /not/ compared to constructors in C++
      2001-05-07 21:08:18  gskluzacek [View]

      • Michael Beam photo + initialize and - init /not/ compared to constructors in C++
        2001-05-08 12:27:34  Michael Beam | O'Reilly Author [View]

1 to 1 of 1