<div dir="ltr"><div class="gmail_extra"><div class="gmail_quote">2013/9/17 Xiangrong Fang <span dir="ltr"><<a href="mailto:xrfang@gmail.com" target="_blank">xrfang@gmail.com</a>></span><br><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex">
<div dir="ltr"><div><div class="gmail_quote"><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><div><div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex">
My question is, since the programmer is responsible for explicitly call
object constructors, then why do we need constructors at all? In
another word, what's the difference<br>
between an object constructor and an object method?<br>
</blockquote>
<br></div></div>
Using the constructor tells the compiler that it should allocate memory on the heap for a new instance,<br>
and return a method to this new memory. There is then an implicit return
value for the constructor, and this is stored in the variable to which
you assign the result of the constructor.<br></blockquote></div></div><span style="font-family:courier new,monospace"><br>Well, could you please explain what's the difference between p1 and p2 in the program below:<br>
<br>
1 program test;<br> 2 type<br> 3 TObj = object<br> 4 public<br> 5 Value: Integer;<br> 6 procedure SetValue(AValue: Integer);<br> 7 constructor Init(AValue: Integer);<br> 8 end;<br> 9 <br> 10 procedure TObj.SetValue(AValue: Integer);<br>
11 begin<br> 12 Value := AValue;<br> 13 end;<br> 14 <br> 15 constructor TObj.Init(AValue: Integer);<br> 16 begin<br> 17 Value := AValue;<br> 18 end;<br> 19 <br> 20 var<br> 21 p1, p2 : ^TObj;<br> 22 begin<br> 23 New(p1);<br>
24 p1^.SetValue(1);<br> 25 WriteLn(p1^.Value);<br> 26 New(p2, Init(2));<br> 27 WriteLn(p2^.Value);<br> 28 end.</span><br></div>
</blockquote></div><br></div><div class="gmail_extra">(Thanks to Michael for spotting that you are using TP objects)<br><br></div><div class="gmail_extra">A little bit below the citation in your first post, you'll find this: "A constructor/destructor pair is <span class="">required </span>if the object uses virtual methods. The reason is that for an
object with virtual methods, some internal housekeeping must be done: this housekeeping is done by the
constructor" :-) In Turbo Pascal, it seems that some VMT housekeeping was also done in the destructor, I don't know if this is still true in fpc.<br></div><div class="gmail_extra">
<br>-- <br>Frederic Da Vitoria<br>(davitof)<br><br>Membre de l'April - « promouvoir et défendre le logiciel libre » - <a href="http://www.april.org" target="_blank">http://www.april.org</a><br>
</div></div>