// Online C++ compiler to run C++ program online
#include <iostream>
#include <iterator>
#include <set>
int index;
int member[5] = {0,1,2,3,4};
class Animal{
public:
Animal(int val){
member[val]=-1;
}
~Animal(){
member[index]=index;
}
};
int main() {
// Write C++ code here
for(int i=0;i<5;i++){
std::cout<<member[i]<<" ";
}
std::cout<<std::endl;
for(int i=0;i<5;i++){
index=i;
Animal a(i);
}
for(int i=0;i<5;i++){
std::cout<<member[i]<<" ";
}
return 0;
}
In following code the output is:
0 1 2 3 4
0 1 2 3 4
But I am interested in the following output:
0 1 2 3 4
-1 -1 -1 -1 -1
So every time we perform Animal a(i); its constructor gets called and member[val]=-1 but immediately after its iteration the destructor gets called which makes the value back to val. member[index]=index.
How can we delay the call to destructor in this case?
I want the member[5]={-1,-1,-1,-,1,-1} after the for loop ends
and member[5]={0,1,2,3,4} restored to original value only when main() exists.