Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of variables global and variables of class in Delphi

Tags:

delphi

I have a question about use of global variables and variables of class using class var.

Declaring variables in class with class var:

unit Unit1;

interface

type
  TClass = class
  public
    class var ObjectList: TObjectList
  end;

implementation
end.

Declaring global variables:

unit Unit1;

interface

var
  ObjectList: TObjectList

implementation
end.

How does the compiler allocate memory for these two variables?

like image 882
Johni Douglas Marangon Avatar asked Feb 24 '14 11:02

Johni Douglas Marangon


People also ask

What is the difference between global variable and class variable?

The main difference between Global and local variables is that global variables can be accessed globally in the entire program, whereas local variables can be accessed only within the function or block in which they are defined.

Can global variables be used in classes?

If you want to use that variable even outside the class, you must declared that variable as a global. Then the variable can be accessed using its name inside and outside the class and not using the instance of the class.

Why do we use global variables?

Variables that are created outside of a function (as in all of the examples above) are known as global variables. Global variables can be used by everyone, both inside of functions and outside.


1 Answers

These variables are implemented in exactly the same way. The class var is implemented as a global variable. That is there is a single instance of the variable in the module, allocated statically.

The only difference is that the class var is in a different scope, and you can use visibility protection specifiers like private to limit access to the variable.

like image 196
David Heffernan Avatar answered Oct 14 '22 14:10

David Heffernan