简体   繁体   中英

How can I access a hidden member from a derived class?

I have two classes, one derived from the other. These classes both introduce variables with the same name. The variable in the derived class hides that in the super class.

How can I refer to the super class's variable from a method of the derived class?

type
  TClass1 = class
  protected
    FMyVar: Integer;
  end;

  TClass2 = class(TClass1)
  protected
    FMyVar: Integer;
  public
    procedure Foo;
  end;

procedure TClass2.Foo;
begin
  //here I want access to FMyVar from TClass1
end;

There's nothing special. Each subclass automatically has access to things from its parent class, except those members that were marked private in the parent.

Sublasses declared in the same unit as their parent have access to members marked private . Use strict private instead to really prevent subclasses from accessing their inherited members.

You can gain access with a cast:

procedure TClass2.Foo;
begin
  DoSomething(TClass1(Self).FMyVar);
end;

As a side note, I suggest you reconsider your design. The path you are taking leads to confusion and bugs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM