tags:

views:

75

answers:

5
class xyz{

...
...
};

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

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

+7  A: 

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.
Alex B
+3  A: 
  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?
ybungalobill
+2  A: 

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.

Oli Charlesworth
+4  A: 

Nope, its scope is limited to the while loop.

KMan
+2  A: 

in each iteration, a completely new object is created. It just so happens they all have the same name xyz. In the end ob the iteration, the current object is destroyed via its destuctor, and in the next iteration a new object with the same name is created. So your code is perfectly fine. HTH

Armen Tsirunyan