1

I have written this simple code:

type
  TTestA = class
  strict protected
    a: integer;
  public
    f: integer;
    constructor Create(x: Integer);
  end;

type
  TTestB = class(TTestA)
  strict private
    c: integer;
  end;

I use strict because these classes are in the same unit as the TForm1 class. Since a is protected by definition, it should be accessible only in subclasses, but then why this code doesn't work?

procedure TForm1.Button1Click(Sender: TObject);
var
  K: TTestB;
begin
  k := TTestB.Create(3);
  value = k.a; //I cannot access a
end;

Also, the protected can be useful to create an abstract class. In C++, if I declare a constructor as protected, I cannot create an instance of the object and only subclasses can. Can Delphi do this?

I am having the same problem with the variable and the constructor.

2
  • You are asking two separate questions. That is against StackOverflow guidelines. Please move your abstract question to another post. Commented May 23, 2017 at 21:09
  • Regarding the first question: Do not make the mistake of confusing classes with units. TForm is not related to either of the classes TTestA or TTestB. But TTestB is a subclass (descendent) of TTestA, so they are related. Commented May 23, 2017 at 21:52

2 Answers 2

7

protected access means "accessible in the class and any sub-class".

This means that a in your example will be accessible to methods in class TTestB but this does not extend to consumers of instances of TTestB (or TTestA).

The code in TForm1 is part of a class which is not a subclass of TTestA.

Put another way, TForm1 does not inherit from TTestA and therefore cannot access any private or protected members of k.

Sign up to request clarification or add additional context in comments.

Comments

5

The answer is in your own question:

Since a is protected by definition it should be accessible only in subclasses

Regardless of the fact that TForm1 uses a local k variable of type TTestB, since TForm1 itself is not a subclass of TTestA, it does not have access to the k.a member. TTestB is a subclass of TTestA, so internally it has access to a.

This is explained in more detail in Embarcadero's documentation:

Classes and Objects (Delphi): Visibility of Class Members

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.