Re: how to overload = operator for pointers
Suresh V <vsuresh.cs@gmail.com>, on 07/07/2010 08:43:13, wrote:
On Jul 7, 8:41 pm, Suresh V<vsuresh...@gmail.com> wrote:
Hi,
I want to copy the contents of one pointer into another pointer which
is of same type by overloading '=' and '()' operator. Please guide me
how to do it. I tried doing it but only got syntax error and some
times crash.
class loc
{
public:
loc::loc() {
}
loc::loc(int longi, int lat) {
longitude = longi;
latitude =lat;
}
loc* operator()(loc op2);
void show();
private:
int latitude;
int longitude;
};
void loc::show()
{
cout<< "long="<< longitude<< " lat="<< latitude<< endl;
}
loc* loc::operator()(loc& op2)
{
cout<< "pointer"<< std::endl;
void* temp = malloc(sizeof(op2));
loc* loci = (loc *)temp;
loci->longitude = op2.longitude;
loci->latitude = op2.latitude;
return loci;
}
int main()
{
loc *new1 = new loc(4, 6);
loc *new2(newLoc);
new2->show();
delete new1;
delete new2;
return 0;
}
But i output
long=4 lat=6
"*** glibc detected *** double free or corruption (fasttop):
0x0000000000502010 ***"
+suresh
Correcting the syntax error:
int main()
{
loc *new1 = new loc(4, 6);
loc *new2(new1);
Apart from what Victor said, with the above statement you're simply
setting new2 to have the same content of new1 - that is, two pointers
storing the same exact address (print them out to see by yourself).
The obvious result is that you get the double deletion - even though the
code you posted isn't at all the code that caused that error, because
your code couldn't be compiled even after the self correction you made
in the follow-up.
Please read the C++ FAQ, you will learn a lot of things - among these,
you'll learn not to carelessly mix up C style memory management with C++
style.
FAQ 5.8 is particularly important: post complete, compilable code -
_the_ code that you compiled and that raised the errors you're
complaining about.
--
FSC - http://userscripts.org/scripts/show/59948
http://fscode.altervista.org - http://sardinias.com