Ankit
Ankit

Reputation: 361

Can I do this with class objects?

class xyz{

...
...
};

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

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

Upvotes: 6

Views: 106

Answers (5)

Yakov Galka
Yakov Galka

Reputation: 72469

  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?

Upvotes: 4

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132984

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

Upvotes: 3

Kamran Khan
Kamran Khan

Reputation: 9986

Nope, its scope is limited to the while loop.

Upvotes: 5

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

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.

Upvotes: 3

Alex B
Alex B

Reputation: 84802

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.

Upvotes: 8

Related Questions