folks, I came across questions about calling constructor or destructor.
I am curious whether you can:
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
So I wrote the following code and want to share with you what I got. Comments are welcomed! Please check if I miss anything.
1. call a constructor in a constructor
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;
}
Basically you are not actually calling the constructor, you are just generating a temp object.
If you use this->A() to call then you will get an error.
Code:
error: calling type `A' like a method
Also this brings a recursive calling. Soon you will use up memory and crash.
2. call a destructor in a constructor
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;
}
You can't call ~A() without qualifying: this->~A(). At least I didn't figure out a way to avoid it.
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
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;
}
Again, you are not calling constructor, just a temp obj.
4. call a destructor in a destructor
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;
}
This also gives you a dead loop.
5. call a constructor in a member function
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;
}
It works. just a temp obj.
6. call a destructor in a member function
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;
}
It works.