Search code examples
delphioopprivateprivate-members

Delphi: writing to the private ancestor's field in descendant class


I need to fix a third-party component. This component's class has private variable which is actively used by its descendants:

TThirdPartyComponentBase = class
private
  FSomeVar: Integer;
public
  ...
end;

TThirdPartyComponent = class (TThirdPartyComponentBase)
protected
   procedure Foo; virtual;
end;

procedure TThirdPartyComponent.Foo;
begin
  FSomeVar := 1; // ACCESSING PRIVATE FIELD!
end; 

This works because both classes are in the same unit, so they're kinda "friends".

But if I'll try to create a new class in a new unit

TMyFixedComponent = class (TThirdPartyComponent)
  procedure Foo; override; 
end;

I can't access FSomeVar anymore, but I need to use it for my fix. And I really don't want to reproduce in my code all that tree of base classes.

Can you advise some quick hack to access that private field without changing the original component's unit if it's possible at all?


Solution

  • You have to use a hack to access a private field in any class (including a base class) in a different unit. In your case define in your unit:

    type
      __TThirdPartyComponentBase = class 
      private 
        FSomeVar: Integer;
      end;
    

    Then get the access:

    __TThirdPartyComponentBase(Self).FSomeVar := 123;
    

    Of course, that is dangerous, because you will need to control changes in the base class. Because if the fields layout will be changed and you will miss this fact, then the above approach will lead to failures, AV's, etc.