Skip to Main Content
Mastering Delphi Programming: A Complete Reference Guide
book

Mastering Delphi Programming: A Complete Reference Guide

by Primož Gabrijelčič
November 2019
Beginner to intermediate content levelBeginner to intermediate
674 pages
15h
English
Packt Publishing
Content preview from Mastering Delphi Programming: A Complete Reference Guide

NewInstance

The proper way to create a singleton in Delphi is not to mess with constructors, but to override the NewInstance and FreeInstance methods.

When an object is created, the compiler firstly calls the NewInstance class method of that object and only then executes the constructor. The NewInstance method is virtual, and so we can easily override it in our singleton class.

The default implementation in TObject.NewInstance calls the InstanceSize method to get the number of bytes that are needed to store the new object, then calls GetMem to allocate that number of bytes, and in the end, it calls InitInstance to fill this memory with zeros.

Instead of all of that, we can change our overridden NewInstance method to always return the same ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Delphi GUI Programming with FireMonkey

Delphi GUI Programming with FireMonkey

Andrea Magni
Delphi Cookbook - Third Edition

Delphi Cookbook - Third Edition

Daniele Spinetti, Daniele Teti

Publisher Resources

ISBN: 9781838989118Other