Search code examples
delphidelphi-xe2

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;

Solution

  • 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.