samedi 30 mai 2015

What is the logic behind these destructor calls

I ran the following code

#include <iostream>
using namespace std;

class Count
{
    private:

        int count;      

    public:

        //Constructor
        Count():count(0) { cout << "Constructor called" << endl; }

        //Destructor
        ~Count() { cout << "Destructor called" << endl; }

        //Display the value.
         Count display() 
         { 
               cout << "The value of count is " << count << endl; 
               return *this;
         }

};

int main()
{
    Count C;
    C.display();
}

Result :-

Constructor called
The value of count is 0
Destructor called
Destructor called

In the above case, the destructor is called twice, one for destruction of the "this" object and one for return from main.

Is my observation correct ??

Can anyone explain me also the temporary object created in this process like why it is created, if created??

Aucun commentaire:

Enregistrer un commentaire