Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pascal

What are normal fields/variables in Pascal classes?

Muhammad Ashir

Pascal classes have fields that can hold data specific to an instance of a class or the class as a whole. There are two kinds of fields, normal and static.

Variables declared in normal fields are local to each instance of the class.

Declaring variables in a normal field

There are two ways to declare a variable in a normal field. The first way is the standard way, the same as the definition of an object.

type  
  myClass=class  
    l : integer;  
  end;

var  
  c1,c2 : myClass;  

begin  
  c1:=myClass.create;  
  c2:=myClass.create;  
  cl1.l:=2;  
  writeln(cl1.l);  
  writeln(cl2.l);  
end.
{$mode objfpc}
type  
  myClass = class  
    l : integer;  
  end;

var  
  cl1,cl2 : myClass;  

begin  
  cl1:=myClass.create;  
  cl2:=myClass.create;  
  cl1.l:=2;  
  writeln(cl1.l);  
  writeln(cl2.l);  
end.

As we can see, the value of the variable l is different for each instance of the class myClass. We can also see that, by default, the member variables are initialized as zero (or the equivalent of zero for other types, such as an empty string for string type).

The other way to declare a variable in a normal field is by using the keyword var.

type  
  myClass=class  
  var  
    l : longint;  
  end;

This definition is equivalent to the standard definition. However, in the standard definition, we have to be careful to put all the variables before we declare any methods.

RELATED TAGS

pascal

CONTRIBUTOR

Muhammad Ashir
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring