folks, I came across questions about calling constructor or destructor.
I am curious whether you can:
So I wrote the following code and want to share with you what I got. Comments are welcomed! Please check if I miss anything.Code:1. call a constructor in a constructor 2. call a destructor in a constructor 3. call a constructor in a destructor 4. call a destructor in a destructor 5. call a constructor in a member function 6. call a destructor in a member function
1. call a constructor in a constructor
Basically you are not actually calling the constructor, you are just generating a temp object.Code:class A{ public: A(){ A(); x = 100; cout<<"A() "<<x<<endl; } int x; ~A(){ x = 0; cout<<"~A() "<<x<<endl; } }; int main() { A obj; return 0; }
If you use this->A() to call then you will get an error.
Also this brings a recursive calling. Soon you will use up memory and crash.Code:error: calling type `A' like a method
2. call a destructor in a constructor
You can't call ~A() without qualifying: this->~A(). At least I didn't figure out a way to avoid it.Code:class A{ public: A(){ this->~A(); x = 100; cout<<"A() "<<x<<endl; } int x; ~A(){ x = 0; cout<<"~A() "<<x<<endl; } }; int main() { A obj; return 0; }
Yes, you can call destructor in the class, and you can see it destructs the member variable x.
3. call a constructor in a destructor
Again, you are not calling constructor, just a temp obj.Code:class A{ public: A(){ x = 100; cout<<"A() "<<x<<endl; } int x; ~A(){ A(); x = 0; cout<<"~A() "<<x<<endl; } }; int main() { A obj; return 0; }
4. call a destructor in a destructor
This also gives you a dead loop.Code:class A{ public: A(){ x = 100; cout<<"A() "<<x<<endl; } int x; ~A(){ this->~A(); x = 0; cout<<"~A() "<<x<<endl; } }; int main() { A obj; return 0; }
5. call a constructor in a member function
It works. just a temp obj.Code:class A{ public: A(){ x = 100; cout<<"A() "<<x<<endl; } int x; void foo() { cout<<"BEFORE foo"<<x<<endl; A(); cout<<"AFTER foo"<<x<<endl; } ~A(){ x = 0; cout<<"~A() "<<x<<endl; } }; int main() { A obj; obj.foo(); return 0; }
6. call a destructor in a member function
It works.Code:class A{ public: A(){ x = 100; cout<<"A() "<<x<<endl; } int x; void foo() { cout<<"BEFORE foo"<<x<<endl; A(); cout<<"AFTER foo"<<x<<endl; } ~A(){ x = 0; cout<<"~A() "<<x<<endl; } }; int main() { A obj; obj.foo(); return 0; }



LinkBack URL
About LinkBacks


