11

Today, one very simple question came to my mind when I had to override TObject's BeforeConstruction method:

Why do TObject methods AfterConstruction and BeforeConstruction have public visibility?

I expected them to be protected. What is the reason they aren't?

I can't imagine a valid purpose to call AfterConstruction or BeforeConstruction without calling the constructor or destructor of that class. Do you?

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
René Hoffmann
  • 2,766
  • 2
  • 20
  • 43
  • 1
    I'm sure this was asked (or maybe not asked, but answered)... – TLama May 08 '15 at 10:12
  • Likely the developer made a mistake – David Heffernan May 08 '15 at 10:19
  • Oh, so [`it's been`](http://stackoverflow.com/q/22540670/960757) about `TObject.InitInstance`, and does not directly answer what you ask. But as you can see, there's more that should've been protected but it's not. Taking back my initial comment... – TLama May 08 '15 at 10:26
  • 1
    Maybe, @DavidHeffernan is right with his assumption. Dr. Bob wrote [this](http://www.drbob42.com/delphi4/d4constr.htm) on Delphi 4. It says that these methods have been `protected` back then. – René Hoffmann May 08 '15 at 10:27
  • 5
    If they were protected but have been made public on a later date, it was very likely not a mistake, bur for a certain purpose. – Rudy Velthuis May 08 '15 at 12:05
  • Having the methods to be public allows you to intercept them using `TVirtualMethodInterceptor` – Johan May 08 '15 at 12:26
  • @Johan Virtual methods can be intercepted irrespective of their visibility. – David Heffernan May 08 '15 at 12:42
  • I had a similar question once: http://stackoverflow.com/questions/22540670/delphi-why-is-tobject-initinstance-public – Sentient May 08 '15 at 16:21

1 Answers1

10

A previous question asked why some other methods are public instead of protected, and the answer was that they at some point needed to be called by utility functions that weren't attached to the class.

TObject.AfterConstruction is called by just such a utility function, System._AfterConstruction. If it were (strict) protected, then that standalone function wouldn't have access to the method.

All the methods of TObject are public.* We can probably find rationales to explain why each method is public, but at a certain point, I suspect that the underlying reason for any given method being public is that all the others are, too.

Once Delphi was released with those methods public, any reduction in their visibility would have risked breaking existing code.


* Except for GetDisposed and CheckDisposed, for some reason. They're relatively new, compared to the bulk of TObject.

Community
  • 1
  • 1
Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467