12

I am using this code

type
 TSomeClass = class(TOBject)
 private
  class var InstanceCount : integer;
  class var TotalInstanceCount : integer;
 public
  class function instances: integer;
  class function totalInstances: integer;
  constructor Create;
  destructor Destroy;
end;

constructor TSomeClass.Create;
begin
 inherited Create;
 Inc(InstanceCount);
 Inc(TotalInstanceCount);
end;

destructor TSomeClass.Destroy;
begin
 Dec(InstanceCount);
 inherited;
end;

class function TSomeClass.instances;
begin
  Result := InstanceCount;
end;

class function TSomeClass.totalInstances;
begin
  Result := TotalInstanceCount;
end;

I want to make an instance counter and I set some class variables as private. The question is very easy, just look at this picture:

enter image description here

As you can see in the red box, there are the class variables that I have declared as private. I don't want them to appear. I only want the public class functions to be able to show the counters. What can I do?

Rob Kennedy
  • 161,384
  • 21
  • 275
  • 467
Raffaele Rossi
  • 2,997
  • 4
  • 31
  • 62
  • Is this class defined in the same unit as this form? – Jerry Dodge Sep 08 '16 at 16:47
  • Yes. Should I put this class in another unit? and then in the main unit where I have the form say 'Uses unitwithclass' – Raffaele Rossi Sep 08 '16 at 16:49
  • 4
    Not necessarily, that just confirms my suspicion. Classes in the same unit can access each other's private members. If I'm not mistaken, I believe `strict private` should do the trick for you. – Jerry Dodge Sep 08 '16 at 16:50
  • Make it as answer. I forgot about the strict since I don't use it very often you are right. It works now :) – Raffaele Rossi Sep 08 '16 at 16:52

1 Answers1

16

As explained in the documentation, A class's private section can be accessed from anywhere within the unit where that class is defined. In order to avoid this, and eliminate access to these private class members from elsewhere in the same unit, use strict private instead.

Of course, if your application's design calls for it, you could also move this class over to another unit, which in turn would produce the effect you're looking for as well.

Jerry Dodge
  • 26,858
  • 31
  • 155
  • 327