Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the actual difference between reference variable and object

I have been reading a lot and now i really confused. Consider an ordinary instantiation:

Sampleclass  instance1  = new Sampleclass();

After reading a lot I came to know that instance1 is a reference variable stored in a stack which contains the memory address of the object's data which is stored in heap.

If this is correct then where is object? instance1 is also a object. Sometimes I have seen only declaration like new Sampleclass(). Is that sufficient for object instantiation?

like image 712
peter Avatar asked Sep 28 '26 08:09

peter


2 Answers

instance1 is a variable.

Because its type is a reference type, it is a reference to an object instance that lives on the heap.

new SampleClass() is a constructor call that creates a new object on the heap and returns a reference to it.

like image 148
SLaks Avatar answered Sep 29 '26 22:09

SLaks


instance1 contains the copy of the reference which points to the memory where new objet Sampleclass() is created. What's confusing is instance1 is mere a copy of a reference, which is different from reference ref (C# Reference), which might confuse you as it confused me.

like image 32
swcraft Avatar answered Sep 29 '26 22:09

swcraft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!