Ivan Prodanov
Ivan Prodanov

Reputation: 35532

Is Inheriting nested classes possible?

Well,I have a parent class with a nested class declared in the "protected" tab with a protected class variable.In another unit I have a child class,which inherits from the parent class.When I try to access something protected/public from the parent class -it works,but when I try to access something protected from the nested class,it doesnt work.

type
  TParent = class(TObject)

  protected
    class var x:integer;
    type
      TNested = class(TObject)

        protected
          class var y:integer;
    end;
end;

My code in the child class:

x := 10; //works
y := 10; //undeclarated idenitifier 'y'.
TNested.y := 10; //undeclarated idenitifier 'y'

the declaration of the child class is:

type
  TChild = class(TParent);

How do I access y?

Upvotes: 2

Views: 1241

Answers (4)

Gerry Coll
Gerry Coll

Reputation: 5975

The example you are giving is using a nested class, not inheriting it.

Nested classed can be inherited in subclasses of the declaring class:

TSubParent = class(TParent)
protected
  type 
   TSubNested = class(TNested)
   public
     class var Z : integer;
   end;
end;

Upvotes: 0

smok1
smok1

Reputation: 2950

y:integer is a protected field of TNested class, ie. can be only used by TNested and it's own inherited classes.
You probably may use TNested from TParent but this is beacause in Delphi you may have greater access than it should be if calling from the same unit. So TParent and TNested are in the same unit, so you may call TNested protected data from TParent. But since TChild is in different unit than TNested, it is impossible.

Upvotes: 3

Ondrej Kelle
Ondrej Kelle

Reputation: 37221

TParent.x := 10;
TParent.TNested.y := 10;

Upvotes: 0

Cobus Kruger
Cobus Kruger

Reputation: 8615

This will actuall work if TChild and TParent are in the same unit, because of the implicit friendship between classes within the unit.

To access y in your example, you'd need to do one of two things:

  1. Change the scope of y to public (or create a public property for it).
  2. Use y from a nested class that is derived from TNested.

Upvotes: 0

Related Questions