class xyz{
...
...
};
while(i<n){
xyz ob;
...
...
}
Do I need to destroy the earlier object before reallocating memory to it?
class xyz{
...
...
};
while(i<n){
xyz ob;
...
...
}
Do I need to destroy the earlier object before reallocating memory to it?
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.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.
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