Let's assume I have a Base-Class 'TClass1' and a derived Class 'TClass2' (and maybe a couple of more derived Classes). I want to be able to query the size of those classes with 2 methods, which I want to declare in the Base-Class:
- 'showSize1' should always report the size of the Base-Class (even if called from 'TClass2' or later derived Classes)
- 'showSize2' should always report the size of the current Class.
With 'size' I mean the number of bytes which are allocated on the heap during 'Create' and are freed during 'Free'.
Method 'showSize2' does want I want: is shows the size of the current class.
But Method 'showSize1' does not want I want: is shows the size of a pointer (which I understand, because a Class type is a pointer). What I do not understand: why can't I use something like sizeof(TClass1^)? What must I do instead?
Thanks in advance.
type
TClass1 = Class
procedure showSize1;
procedure showSize2;
private
v1: integer;
v2: longint;
end;
TClass2 = Class(TClass1)
private
v3: double;
v4: string[40];
end;
procedure TClass1.showSize1;
begin
writeln(sizeof(self)); // shows the size of a pointer
writeln(sizeof(TClass1)); // shows the size of a pointer
// writeln(sizeof(self^)); // does not compile
// writeln(sizeof(TClass1^)); // does not compile
end;
procedure TClass1.showSize2;
begin
writeln(self.InstanceSize); // shows the size of the current class
end;
procedure test;
var C1: TClass1;
C2: TClass2;
begin
C1:=TClass1.Create;
C1.showSize1;
C1.showSize2;
C1.Free;
C2:=TClass2.Create;
C2.showSize1;
C2.showSize2;
C2.Free;
end;