[fpc-pascal] Constructors & Destructors 101

Nikolay Nikolov nickysn at users.sourceforge.net
Sun Apr 5 11:57:04 CEST 2009


Jonas Maebe wrote:
>> If you had two different create constructors (for whatever reason), 
>> might you not also need two different destroy destructors?
>
> No, the default destructor should always free all resources, 
> regardless of how the class instance was created. Otherwise, it would 
> also make your code more complex, because throughout the code you 
> would have to track how the instance was created, so that in the end 
> you could call the correct destructor.
I think there's something even more subtle than that. If a constructor 
blows up and raises an exception, the destructor Destroy is called 
automatically to clean up the partially created class, before the 
exception is handled. So, it's not just .free that is hardcoded to call 
destroy. IOW it is an extremely bad idea to have a destructor other than 
Destroy for classes and IMO shouldn't be allowed by the language. 
However, having multiple constructors is perfectly fine, as long as the 
destructor is only one.




More information about the fpc-pascal mailing list