Artik
Artik

Reputation: 805

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;

Upvotes: 1

Views: 471

Answers (2)

David Heffernan
David Heffernan

Reputation: 612854

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.

Upvotes: 5

Rob Kennedy
Rob Kennedy

Reputation: 163257

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.

Upvotes: 5

Related Questions