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; } | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
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; }

31st Aug 2016, 7:23 PM
Lekhraj Singh
Lekhraj Singh - avatar
2 Réponses
+ 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.
31st Aug 2016, 7:43 PM
Zen
Zen - avatar
+ 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...
31st Aug 2016, 8:50 PM
Fardad Fateh