I'm little confused about my this code.
#include <iostream>
using namespace std;
class A{
public:
A(){
cout << "Constructor" << endl;
}
~A(){
cout << "Destructor" << endl;
}
void operator ~(){
cout << "\nOverloaded Operator";
}
};
int main(){
~A();
cout << "\nBefore End";
}
Output
Constructor
Overloaded OperatorDestructor
Before End
I want to ask that on ~A(); line of code constructor A(); creates the object, then that object is calling the operator? If not then please explain how it's working. Thanks.
A() creates a temporary of type A, that you invoke operator~() on, and which gets destroyed at the end of the line.
The destructor is a special member function - but it's still a member function. As such, if you're going to invoke it directly - which should be done in only rare, special cases - it still has to be invoked on an object. For instance, this example will invoke the destructor:
A().~A();
However, it will destroy that A temporary twice, which is bad.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With