Consider this class:
unit Unit2;
interface
type
TTeste = class
private
texto: string;
public
function soma(a, b: integer): string;
end;
implementation
procedure TForm2.Button1Click(Sender: TObject);
var
teste: TTeste;
begin
teste:= nil;
teste.texto:= '';//access violation
showmessage(teste.soma(5, 3));//no access violation
end;
{ TTeste }
function TTeste.soma(a, b: integer): string;
begin
result:= (a+b).ToString;
end;
end.
should it really work? why? the var crashed but the function doesnt, does it works like a class funtion?
The relationship between object and class is the same as the one between variable and type. As in most other modern OOP languages (including Java and C#), in Delphi a class-type variable doesn't provide the storage for the object, but is only a pointer or reference to the object in memory.
He is also proficient in XML, DHTML, and JavaScript. In Delphi, a method is a procedure or function that performs an operation on an object. A class method is a method that operates on a class reference instead of an object reference.
The Create constructor is a class method, as opposed to virtually all other methods you'll encounter in Delphi programming, which are object methods. A class method is a method of the class, and appropriately enough, an object method is a method that can be called by an instance of the class.
The Delphi compiler allows an alternative syntax to class types. You can declare object types using the syntax: type objectTypeName = object ( ancestorObjectType ) memberList end; where objectTypeName is any valid identifier, ( ancestorObjectType) is optional, and memberList declares fields, methods, and properties.
This works because you are not attempting to access any fields of the class. The function doesn't require any memory allocation. If the field texto
was used in that function, then it would crash (as you see in your other test), because that memory isn't addressed. But here, there is no memory involved. Both a
and b
(and the function result for that matter) are allocated elsewhere outside of the class. Part of the instantiation process is allocating memory for each and every one of the fields in the object.
This is just coincidental. It's still highly discouraged to actually use something like this. If you feel the need to access the function without instantiation, then you should make it a class function instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With