mmm mmm - 1 year ago 53
C++ Question

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 // extra call to destructor

11

inside loc destructor // extra call to destructor

11

inside loc destructor

11

inside loc destructor


Answer Source

This is because of

ob3 = ++ob1;

Look at this code more carefully

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

So what can you do to avoid this extra copy.. You can return by reference

const loc&  operator++(){
   cout<<"inside pre incriment"<<endl;
   ++iVAL;
   return *this; <--- you create a new copy and send it back
}

The above code returns by reference and the const pointer is prevent others from modifying your value.

However the code you have written for pre increment is wrong It should retun the value before increment.

So the code should be something like this

loc operator++(){
   cout<<"inside pre incriment"<<endl;
   int  temp = iVAL;
   ++iVAL;
   return temp; <--- you create a new copy and send it back
}

In this case you cannot return by reference between temp is a temporary variable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download