This program is designed with custom class A which outputs 1 when the copy constructor is called, and 0 when the destructor is called.
I copied twice, and deleted twice, yet the destructor was called 3 times, resulting in an output of 11000. Why is this the case?
#include <iostream>
using namespace std;
class A {
public:
float v;
A() {v = 1.0;}
A(A &a) {A::v = a.v; cout << "1";}
~A() { cout << "0";}
float set(float v){
A::v = v;
return v;
}
float get(float v){
return A::v;
}
};
int main(){
A a, *b = new A(a), *c = new A(*b); // output 110 (Not sure why the destructor is called in this line)
c->get(b->get(a.set(1.0)));
delete b; // output 0
delete c; // output 0
return 0;
}
I tried commenting out lines of code, and through doing so have narrowed down the extra destructor call to this line:
A a, *b = new A(a), *c = new A(*b);
However, I still don't understand why the destructor is being called here.
The destructor isn't called in that line. It is called when
A ais destroyed. You can get a better view of what's happening when you distinguish the different objects by initializing the member with different value:output is:
delete bprints2,delete cprints3,std::cout << "bye \n"printsbyeand whenmainreturnsais destroyed too which prints1.