This question arose from an issue that surfaced when using method chaining (fluent interface), and I suppose that's one of the only reasons it might be an issue at all.
To illustrate, I'll use an example using method chaining:
In unit A:
TParent = class
protected
function DoSomething: TParent;
end;
In unit B:
TChild = class(TParent)
public
procedure DoAnotherThing;
end;
implementation
procedure TChild.DoAnotherThing;
begin
DoSomething.DoSomething
end;
I want to keep the DoSomething procedure protected and visible only to class descendants.
This won't compile, throwing a
cannot access protected symbol TParent.DoSomething
because DoSomething returns a TParent and the subsequent DoSomething call is issued from a TParent object in another unit (so the protection kicks in and the function is inaccessible). (thanks, David Heffernan, for the explanation)
To reduce it to its bare essence, something like TParent(Self).DoSomething is not possible inside the TChild class.
My question:
since the compiler does know that a copy of the Self parameter is being accessed from within the child class, would there be instances in which the ability to access the ancestor's protected methods breaks encapsulation? I'm only talking about dereferencing the typecasted Self from inside a descendant's class method. I'm aware that outside of this class, that parameter should not have access to the ancestor's protected methods (in another unit), of course.
Again, in short: when a variable, that is identical to the Self parameter, is dereferenced INSIDE one of its own class methods, would it be unsafe for the compiler to allow it access to its parent's protected methods (just like the Self parameter itself)?
It's a pretty theoretical question, but I'd be interested if it would have any negative impact on compiled code or encapsulation, if the compiler would allow this.
Thanks.