How to Define Inheritable Record/Structure in Delphi (Object Pascal)?


In Delphi (Object Pascal), you can use the record keyword to define a C-like structure. For example,

type data = record
  key: string;
  value: integer;
end;

It is interesting to know that you can use the object keyword to do the same thing, like this:

type A = object
   x: integer;
end;

The sizeof(A) = 4 bytes. But you can inherit this, in a object oriented manner:

type B = object(A)
   y: integer;
end;

Now, the record B has size 8 bytes and can access both x and y fields. And this inheritance chain can keep going. The advantage of doing so is that you avoid re-define the common data fields if multiple data structures share the same fields e.g. Teacher and Student should have common fields like Name, Age which can be included in a common data record.

type
  Human = object
    name: string;
    age: integer;
  end;

  Teacher = object(Human)
    teacherID: string;
    subject: string;
  end;

  Student = object(Human)
    studentID: string;
    score: integer;
  end;

Now, you can do something polymorphism:

var
  tom, jack: Human;
  tina: Student;
  jim: Teacher;

begin
  tom := tina;
  jack := jim;
end;

You can re-assign a base type (e.g. Human) to a more concrete type (children data type) e.g. Teacher or Student. Please also note that the assignment between data record in Delphi (Object Pascal) is copy by value. And Like ‘packed record’ you can also ‘packed object’ which will save storage space.

datastructures How to Define Inheritable Record/Structure in Delphi (Object Pascal)? data structure data types delphi

inheritable data structures

This inheritable data structure is supported/tested from Delphi 7 so this should be also available in your modern Delphi compilers such as Berlin.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
392 words
Last Post: How to Generate 100K Test Data to MySQL Database?
Next Post: The K Nearest Neighbor Algorithm (Prediction) Demonstration by MySQL

The Permanent URL is: How to Define Inheritable Record/Structure in Delphi (Object Pascal)?

Leave a Reply