Recent

Author Topic: Calling a Class Constructor  (Read 3849 times)

Handoko

  • Hero Member
  • *****
  • Posts: 5403
  • My goal: build my own game engine using Lazarus
Calling a Class Constructor
« on: December 23, 2021, 04:32:55 am »
Someone asked me why the syntax analyzer accepts the line #10, there were no compile error, warning, nor hint. I don't know. Can anyone please provide an explanation?
https://forum.lazarus.freepascal.org/index.php/topic,57604.msg428688.html#msg428688

Code: Pascal  [Select][+][-]
  1. type
  2.   TNumber = class
  3.     // ...
  4.   end;
  5.  
  6. procedure TForm1.Button1Click(Sender: TObject);
  7. var
  8.   N1: TNumber;
  9. begin
  10.   N1.Create;
  11. end;

PascalDragon

  • Hero Member
  • *****
  • Posts: 5938
  • Compiler Developer
Re: Calling a Class Constructor
« Reply #1 on: December 23, 2021, 09:07:48 am »
Someone asked me why the syntax analyzer accepts the line #10, there were no compile error, warning, nor hint. I don't know. Can anyone please provide an explanation?

A constructor is called like a normal method if called on an instance variable or within an instance (e.g. if you call another constructor of the same class within the class' constructor it's called as a normal method). Of course this leads to trouble if the instance was never created like in your example. ;) (And yes, it's a common mistake and sometimes even happens to experienced Object Pascal developers :-[ )

dseligo

  • Hero Member
  • *****
  • Posts: 1500
Re: Calling a Class Constructor
« Reply #2 on: December 23, 2021, 12:50:29 pm »
A constructor is called like a normal method if called on an instance variable or within an instance (e.g. if you call another constructor of the same class within the class' constructor it's called as a normal method). Of course this leads to trouble if the instance was never created like in your example. ;) (And yes, it's a common mistake and sometimes even happens to experienced Object Pascal developers :-[ )

It would be great if there is a warning, something like: Variable 'N1' does not seem to be initialized.

 

TinyPortal © 2005-2018