2
votes

I am trying to understand precisely how Delphi manages the memory and I have read from Marco Cantu that it uses references like Java does.

I have understood that a variable (let's say var theObj: TSomeClass;) holds a reference (= a pointer) to indicate the memory location where the object has been stored. So when I call the constructor of theObj I am creating the class on the heap and then theObj is a pointer to the newly created location.


So far so good but now I have the doubt. He says that:

In some OOP languages, declaring a variable of a class type creates an instance of that class.

Does this mean that a pointer to a memory location is not involved? My guess is that here you declare a variable and it directly creates the object without using the heap. So is the variable only create on the stack and it holds all the data of the class?


Note. The guess and the question above are made because I made a comparison with C++.

  • Delphi: theObj := TSomeClass.Create
  • C++: TSomeClass *theObj = new TSomeClass;

Not going off topic and talking of C++ (it was just as example, I know only this language to make the comparison) but here in both cases I create the object in the heap and I have a pointer to it. The second question I made above came out because of this: in C++ I can also create an object like this TSomeClass theObj; and it will live until the end of the scope of the function.

In Delphi I cannot. I think that marco refers so this when he says "declaring a variable of a class type creates an instance of that class". Am I correct?

1
I think you may be reading him wrong, when he says "In some OOP languages, declaring a variable ..." he is drawing a distinction between those languages and Delphi. In the very next sentence, he says "Delphi, instead, is based on an object reference model.. Note the instead.MartynA

1 Answers

4
votes

Marco is thinking of C++ where classes and structs are essentially the same with different default accessibility. In C++

SomeClass obj;

creates the object.

There is nothing for you to worry about. Your understanding, as expressed in the second paragraph, is impeccable. A Delphi variable of class type is, under the hood, just a pointer to the instance.