c++ - Why are there two extra calls to destructor as I have created only two objects and using overloaded assignment operator and increment operator -


#include <iostream> using namespace std;  class loc{      int ival;  public:      loc(int i){         cout<<"inside parameter constructor"<<endl;         ival = i;     }      loc(){          ival = 0;         cout<<"inside default constructor"<<endl;     }      loc operator+(loc ob1){         loc temp;         temp.ival = ival + ob1.ival;         return temp;     }     void show(){         cout<<ival;     }      loc  operator++(){         cout<<"inside pre increment"<<endl;         ++ival;         return *this;     }      loc operator++(int x){         cout<<"inside post increment"<<endl;         ival++;         return *this;     }      loc operator=(loc &ob){         cout<<"inside assignment"<<endl;         ival = ob.ival;         return *this;     }      ~loc(){         cout<<this->ival<<endl;         cout<<"inside loc destructor"<<endl;     } };  int main(int argc, char* argv[]){      loc ob1(10),ob3;      ob3 = ++ob1;      return 0; } 

output:

inside parameter constructor
inside default constructor
inside pre increment
inside assignment
11
inside loc destructor // call destructor
11
inside loc destructor // call destructor
11
inside loc destructor
11
inside loc destructor

this because of

ob3 = ++ob1; 

look @ code more carefully

loc operator++(){ cout<<"inside pre incriment"<

so can avoid copy.. can return reference

const loc&  operator++(){    cout<<"inside pre incriment"<<endl;    ++ival;    return *this; <--- create new copy , send } 

the above code returns reference , const pointer prevent others modifying value.

however code have written pre increment wrong should retun value before increment.

so code should this

loc operator++(){    cout<<"inside pre incriment"<<endl;    int  temp = ival;    ++ival;    return temp; <--- create new copy , send } 

in case cannot return reference between temp temporary variable.


Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -