Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I do this with class objects?

Tags:

c++

class

class xyz{

...
...
};

while(i<n){
           xyz ob;
           ...
           ...
}

Do I need to destroy the earlier object before reallocating memory to it?

like image 979
Ankit Avatar asked Oct 10 '10 09:10

Ankit


4 Answers

No.

  1. ob is a stack-allocated object, so its own lifecycle is managed automatically. It's constructed at the place where you declare it, destructed at "}".
  2. Since every while iteration is the separate { ... } scope, the object will be constructed and destructed each iteration.
like image 89
Alex B Avatar answered Nov 11 '22 14:11

Alex B


Nope, its scope is limited to the while loop.

like image 25
KMån Avatar answered Nov 11 '22 13:11

KMån


  1. You mean define an object not declare (removed from question).
  2. Yes you can do that.
  3. No you don't need to destroy it since it's destroyed automatically. The memory is allocated on the stack and will be reused anyway. The compiler can even optimize it in many cases. And HOW could you reallocate the memory anyway?
like image 4
Yakov Galka Avatar answered Nov 11 '22 13:11

Yakov Galka


No. The scope of ob ends at the closing brace. The compiler automatically calls the destructor on stack-based objects when they go out of scope.

like image 3
Oliver Charlesworth Avatar answered Nov 11 '22 13:11

Oliver Charlesworth