Bascy
Bascy

Reputation: 2089

How to override a Class property getter in Delphi

I'v defined a base class and some derived classes, that will never be instantiated. They only contain class functions, and two class properties.

The problem is that Delphi demands that the property get method of a class property is declared with static keyword en therefore cannot be declared virtual, so i can override it in the derived classes.

So this code will result in a compile error:

    TQuantity = class(TObject)
    protected
      class function GetID: string; virtual; //Error: [DCC Error] E2355 Class property accessor must be a class field or class static method
      class function GetName: string; virtual;
    public
      class property ID: string read GetID;
      class property Name: string read GetName;
    end;

    TQuantitySpeed = class(TQuantity)
    protected
      class function GetID: string; override;
      class function GetName: string; override;
    end;

So the question is: How do you define a class property whose resulting value can be overridden in derived classes?

Using Delphi XE2, Update4.

Update: Solved it with the suggestion of David Heffernan using a function in stead of a property:

    TQuantity = class(TObject)
    public
      class function ID: string; virtual;
      class function Name: string; virtual;
    end;

    TQuantitySpeed = class(TQuantity)
    protected
      class function ID: string; override;
      class function Name: string; override;
    end;

Upvotes: 4

Views: 4749

Answers (2)

Mega WEB
Mega WEB

Reputation: 89

type
  // Abstraction is used at sample to omit implementation
  TQuantity = class abstract
  protected
    class function GetID: string; virtual; abstract;
    class procedure SetID(const Value: string); virtual; abstract;
  public
    // Delphi compiler understands class getters and setters
    {class} property ID: string read GetID write SetID;
  end;

var
  Quantity: TQuantity;

begin
  Quantity.ID := '?';

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612993

How do you define a class property whose resulting value can be overridden in derived classes?

You cannot, as is made clear by the compiler error message:

E2355 Class property accessor must be a class field or class static method

A class field is shared between two classes that are related by inheritance. So that cannot be used for polymorphism. And a class static method also cannot supply polymorphic behaviour.

Use a virtual class function rather than a class property.

Upvotes: 4

Related Questions