Constructor and overloaded operator ordering

I am a 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, what in ~A();

the constructor line of the code A();

creates an object, then this object calls the operator? If not, please explain how it works. Thank.

+3


source to share


2 answers


A()

creates a temporary type A

that you call operator~()

on and that is destroyed at the end of the line.

The destructor is a special member function, but it is still a member function. Thus, if you are going to refer to it directly - which should only be done in rare, special cases - it should still be called on the object. For example, this example will call the destructor:



A().~A();

      

However, it will destroy twice A

, which is bad.

+5


source


To make it more noticeable, enclose the ~ A () call in curly braces

int main(){
    {   
            ~A();
    }
    cout << "\nBefore End";
}

      

So, first a temporary object will be created that calls the default constructor. Then the member function will be called operator ~

and upon completion of the statement the destructor will be called.

This call

~A();

      

equivalent to



A().operator ~();

      

If you write for example the following way

A().A::~A();

      

or

A().~A();

      

then in this case the destructor will be named and the program will have undefined behavior because woulb's destructor will be called twice.

+3


source







All Articles