Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declaring objects in C++ vs java

I have been using c++ for a while now and I am learning java,

declaring objects in java is confusing me,

In java we write

myclass myobject = new myclass();
myobject.mymethod();

Is it same as this code in c++ ?

myclass *myobject = new myclass();
myobject->mymethod();

i.e is the memory getting allocated on heap? If it is on heap why we never free the memory. I believe the new keyword is the same. If so, how do we allocate memory on stack?

like image 475
BitFlip Avatar asked Oct 15 '25 11:10

BitFlip


1 Answers

Is it same as this code in c++ ?

Yes. It's the same.

i.e is the memory getting allocated on heap?

Yes it.

If it is on heap why we never free the memory.

The object is allowed to garbage collector when it is no more reachable. i.e when there are no valid reference to that object or (de-referenced)

If so, how do we allocate memory on stack?

When the particular thread execution starts, variables related to that thread will be placed on stack and will be remove immediately once the job of that thread finished. Every thread has it's own stack.

like image 121
Suresh Atta Avatar answered Oct 17 '25 01:10

Suresh Atta



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!