Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide a protected procedure of an object?

In one base class, there's a protected procedure. When inheriting that class, I want to hide that procedure from being used from the outside. I tried overriding it from within the private and even strict private sections, but it can still be called from the outside. The Original class is not mine, so I can't change how TOriginal is defined.

Is it possible to hide this procedure in my inherited class? And how?

type
  TOriginal = class(TObject)
  protected
    procedure SomeProc;
  end;

  TNew = class(TOriginal)
  strict private
    procedure SomeProc; override;
  end;
like image 252
Jerry Dodge Avatar asked Feb 22 '12 17:02

Jerry Dodge


Video Answer


2 Answers

Protected methods are already hidden from the outside. (Mostly; see below.) You cannot reduce the visibility of a class member. If the base class declared the method protected, then all descendants of that class may use the method.


In Delphi, other code within the same unit as a class may access that class's protected members, even code from unrelated classes. That can be useful sometimes, but usually to work around other design deficiencies. If you have something that's "really, really" supposed to be protected, you can make it strict protected, and then the special same-unit access rule doesn't apply.

like image 96
Rob Kennedy Avatar answered Oct 05 '22 04:10

Rob Kennedy


Once exposed you can not hide it but you can do this to spot where it is called in limit way

TOriginalClass = class
public
  procedure Foo;
end;

TNewClass = class(TOriginalClass) 
public
  procedure Foo; reintroduce;
end;

implementation

procedure TNewClass.Foo;
begin
  Assert(False, 'Do not call Foo from this class');
  inherited Foo;
end;

var Obj: TNewClass;
Obj := TNewClass.Create;
Obj.Foo; // get assert message

Will not get Assert error if declared as TOriginalClass
var Obj: TOriginalClass;
Obj := TNewClass.Create;
Obj.Foo; // Never get the assert message
like image 36
APZ28 Avatar answered Oct 05 '22 03:10

APZ28