Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor and Overloaded Operator Execution Order

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.

like image 554
Asif Mushtaq Avatar asked May 02 '26 11:05

Asif Mushtaq


1 Answers

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.

like image 71
Barry Avatar answered May 04 '26 01:05

Barry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!