Reputation: 361
class xyz{
...
...
};
while(i<n){
xyz ob;
...
...
}
Do I need to destroy the earlier object before reallocating memory to it?
Upvotes: 6
Views: 106
Reputation: 72469
Upvotes: 4
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
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
Reputation: 84802
No.
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 "}"
.while
iteration is the separate { ... }
scope, the object will be constructed and destructed each iteration.Upvotes: 8