Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

pascal

What are class field variables in Pascal?

Samia Ishaque

Overview

Just as objects have fields, classes also have field variables. The scope of these variables is within class methods, but they can also be called from outside with the proper naming convention.

How to define class field variables

There are two methods that can be used to define class field variables.

Using static modifier

This is when you can use the class’s name to reference class variables. The following is an example that will help you understand this method of defining class field variables.

In the below code, cls is a class and l is the field variable. We create two instances of the cls class called var1 and var2 using cls.create. Once created, we define the field variable l for both of these class instances. All three of them, var1, var2, and cls, store the same value of the field variable.


program Hello;
{$mode objfpc}  
type  
  cls=class  
    l : longint;static;  
  end;  
var  
  var1,var2 : cls;  
begin  
  var1:=cls.create;  
  var2:=cls.create;  
  var1.l:=10;  
  writeln(var2.l);  
  var2.l:=20;  
  writeln(var1.l);  
  Writeln(cls.l);  
end. 

Using class var

You can define class variables in a class var block. Following is an example of how this can be done. This code is similar to the one above, except we use class var to define l.

program Hello;
{$mode objfpc}  
type  
  cls=class  
  class var  
    l : longint;  
  end;  
var  
  var1,var2 : cls;  
begin  
  var1:=cls.create;  
  var2:=cls.create;  
  var1.l:=10;  
  writeln(var2.l);  
  var2.l:=20;  
  writeln(var1.l);  
  Writeln(cls.l);  
end. 

Moreover, a class variable is specific to one class and cannot be used by other classes unless they are descendants of the aforementioned class. The following code will throw an error, as we are trying to access one class’s field variable for another class. This is because l is only defined for cls and not cls2, so var2, which is an instance of cls2 cannot access l.

{$mode objfpc} 
program Hello;
type  
  cls=class  
  class var  
    l : longint;  
  end;
  cls2=class;
var  
  var1: cls;
  var2: cls2;
begin  
  var1:=cls.create;  
  var2:=cls2.create;  
  var1.l:=10;  
  writeln(var2.l);  
  var2.l:=20;  
  writeln(var1.l);  
  Writeln(cls.l);  
end. 

RELATED TAGS

pascal

CONTRIBUTOR

Samia Ishaque
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring