Delphi/Lazarus: Difference between restrict, private, and protected Access Modifiers


/ Published in: Delphi
Save to your folder(s)

The difference between private, protected and public is pretty straightforward:

*Private members/methods are only visible within the class that declares them.

*Protected members/methods are visible within the class, and to all subclasses.

*Public members and methods are visible to all other classes.

In Delphi there's a "bug" that makes the visibility of all members public within the same unit. The strict keyword corrects this behaviour, so that private is actually private, even within a single unit. For good encapsulation I would recommend always using the strict keyword.


Copy this code and paste it in your HTML
  1. type
  2. TFather = class
  3. private
  4. FPriv : integer;
  5. strict private
  6. FStrPriv : integer;
  7. protected
  8. FProt : integer;
  9. strict protected
  10. FStrProt : integer;
  11. public
  12. FPublic : integer;
  13. end;
  14.  
  15. TSon = class(TFather)
  16. public
  17. procedure DoStuff;
  18. end;
  19.  
  20. TUnrelated = class
  21. public
  22. procedure DoStuff;
  23. end;
  24.  
  25. procedure TSon.DoStuff;
  26. begin
  27. FProt := 10; // Legal, as it should be. Accessible to descendants.
  28. FPriv := 100; // Legal, even though private. This won't work from another unit!
  29. FStrictPriv := 10; // <- Compiler Error, FStrictPrivFather is private to TFather
  30. FPublic := 100; // Legal, naturally. Public members are accessible from everywhere.
  31. end;
  32.  
  33. procedure TUnrelated.DoStuff;
  34. var
  35. F : TFather;
  36. begin
  37. F := TFather.Create;
  38. try
  39. F.FProt := 10; // Legal, but it shouldn't be!
  40. F.FStrProt := 100; // <- Compiler error, the strict keyword has "made the protection work"
  41. F.FPublic := 100; // Legal, naturally.
  42. finally
  43. F.Free;
  44. end;
  45. end;

URL: http://stackoverflow.com/questions/1516493/difference-between-strict-private-and-protected-access-modifiers-in-delphi

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.