0
why this output 4 not 5; #include<iostream> using namespace std; class A{ public: int x=3; A(){x++;} ~A(){x++;} }; int main() { A obj; cout<<obj.x; }
2 Respostas
+ 3
When you print obj.x, obj hasn't been destroyed yet, so x has been incremented only once (when instanciating obj). Besides, if you were to destroy obj, x would be incremented but deleted right after along with obj.
+ 1
In int main you create an object named "obj" but you didnt destroy it...so just constructor function will work...and writing "x++" in destructor wont do anything good and I think it will result in error(if you destroy an object) because destructor works when an object is destroyed and when it is destroyed you dont have any "x" so x cant be increased...