Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I able to access private class variables from outside the class, and how can I prevent it?

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?

like image 286
Raffaele Rossi Avatar asked Sep 08 '16 16:09

Raffaele Rossi


People also ask

How can you allow access to private class member variables from outside the class?

We can access a private variable in a different class by putting that variable with in a Public method and calling that method from another class by creating object of that class.

Can private fields be accessed outside of the class?

They are only accessible from inside the class. On the language level, # is a special sign that the field is private. We can't access it from outside or from inheriting classes. Private fields do not conflict with public ones.

Which type of variable Cannot be accessed outside the class?

Private members are not visible from outside the class. The default visibility allows access by other classes in the package. The protected modifier allows special access permissions for subclasses.


1 Answers

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.

like image 144
Jerry Dodge Avatar answered Sep 20 '22 15:09

Jerry Dodge