|
-
June 20th, 2011, 11:28 PM
#13
Re: need little help of bug fixers.
 Originally Posted by vkash
I know why it was wrong there when i return a class x data from operator+ to main then it is temporary just as it comes to main it is sent to operator= is called which is taking a temporary data this makes error(in some cases wrong deletion of data). other sources of error are deleting that memory which is even not initialized that's why i put tk function(to initialize if not initialized) .
I think my explanation is not fully correct (copy constructor copy data).
why returning by reference not work
Code:
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include<iostream>
using namespace std;
class x
{
private:
int i;
int* p;
public:
x(int xi,int xp);
x(const x&);
~x();
void get() const;
int geti() const ;
int getp() const;
x& operator=(const x&);
x& operator+(const x&);
void change(int ,int);
void tk()
{
cout<<"tk\n";
i =1;
p=new int(0);
}
};
static int m(0);
x::x(int xi=1,int xp=1)
{
cout<<"constructor start..."<<xi<<endl;
bool d(0);
if((xi>1000)||(xp>1000)||(xi<0)||(xp<0))
{
cout<<"setting by default large data"<<xi<<xp<<" \n";
d=1;
}
i=xi;
p=new int(xp);
if(d==1)
{
i=1;
p=new int(1);
}
m++;
cout<<"constructor end..."<<m<<endl<<endl;
}
x::x(const x& xc)
{
cout<<"copy constructor start ..."<<endl;
//cout<<"going to copy in "<<i<<" "<<*p<<endl;
p=0;
int it=xc.geti();
int pt=xc.getp();
this->change(it,pt);
m++;
cout<<"copy constructor end ..."<<endl;
}
static int j;
x::~x()
{
cout<<"destructor start..."<<i<<endl;
delete p;
j++;
cout<<"destructor end ..."<<j<<endl<<endl;
}
void x::get() const
{
cout<<"void get() start ..."<<endl;
cout<<"*******: "<<i<<endl;
cout<<"pointer: "<<*p<<endl;
cout<<"void get() end ... "<<endl<<endl;
}
int x::geti() const
{
return i;
}
int x::getp() const
{
int a=*p;
return a;
}
void x::change(int a,int b)
{
cout<<"void change() start ..."<<endl;
i=a;
delete p;
int*op=new int(b);
p=op;
cout<<"void change() end ..."<<endl;
}
x& x::operator=(const x& xn)
{
cout<<"operator= start..."<<endl;
int it=xn.i;
int pt=xn.getp();
change(it,pt);
cout<<"operator= end ..."<<endl;
return *this;
}
x& x::operator+(const x& xop) //here returning by reference not work
{
cout<<"opearator+ start...\n";
int itmp=this->geti()+xop.geti();
int ptmp=this->getp()+xop.getp();
//x* xreturn=new x(itmp,ptmp);
x tr(itmp,ptmp);
cout<<"operator+ end ..."<<"\n";
return tr;//x(itmp,ptmp);//*xreturn;
}
int main()
{
{
x x3;
x x2(10,20);
x x4(100,200);
x3=(x4+x2);
cout<<"result"<<endl;
x3.get();
}
cout<<m<<" "<<j<<endl;
_CrtDumpMemoryLeaks();
return 0;
}
It hangs in between execution.
I can't explain why returning by reference not work. Can you please explain?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|