2

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
  • 4
    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. Commented May 28, 2017 at 14:36

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This took me 2 days, thanks for your confirm now I know that it's correct. I see that Delphi and C++ both use the pointer to memory thing but C++ also has another way to create an object and he was referring to it. Thank you a lot btw!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.