C++ question, please help.

notfred

Lifer
Feb 12, 2001
38,241
4
0
Ok, I've got a copy constructor for a class. I'm not gonig to post it here, because it works fine. However, when tryingto overload the = operator, it doesn't work so well.

WumpusList WumpusList::eek:perator=(WumpusList w){
WumpusList newlist = w;
cout << "list passed to =:\n";
w.PrintList();
cout << "end list\n";

cout << "list returned by =\n";
newlist.PrintList();
cout << "end list\n";

return newlist;
}

when the lists are printed, theyboth show as equal. however if I call this fuction like:
WumpusList list1;
WumpusList list2;
// stuff to fill list1 here
list2 = list1; // this line returns NOTHING.

What am I doing wrong?

this:

WumpusList list1;
// stuff to fill list1 here
WumpusList list2 = List1;

works fine

Help?
 

virtuamike

Diamond Member
Oct 13, 2000
7,845
13
81
In order to overload operator= like you want, you need to declare it as a friend. The way you have it set up right now, it's a new constructor, not a copy constructor.

** EDIT **
Actually don't quote me on that, I haven't done C++ in like 2 years.
 

Ameesh

Lifer
Apr 3, 2001
23,686
1
0
lol i just saw it, your list that you are creating in side the function is local scope you cant pass that out unless you attach a pointer that was passed in



example this is what your doing:


//class foo has a bunch of members


foo dummy_function(foo apple)
{
foo temp = new foo(apple); // making a new list with apple going inside the copy constructor
return temp; // Ooops! i'm returning a local variable once this returns its out of scope and the calller can not see it.
}



 

Ameesh

Lifer
Apr 3, 2001
23,686
1
0


<< In order to overload operator= like you want, you need to declare it as a friend. The way you have it set up right now, it's a new constructor, not a copy constructor.

** EDIT **
Actually don't quote me on that, I haven't done C++ in like 2 years.
>>





decalring an overloaded operator as friend is proper style but you dont have to do it. i do think you should though for obvious reasons (if its not obvious look up what a friend is)
 

Ameesh

Lifer
Apr 3, 2001
23,686
1
0


<< const WumpusList & WumpusList::eek:perator=(const WumpusList &w) >>



still wouldnt solve it he is allocating the memeory for his new list locally.
 

notfred

Lifer
Feb 12, 2001
38,241
4
0


<<

<< const WumpusList & WumpusList::eek:perator=(const WumpusList &w) >>



still wouldnt solve it he is allocating the memeory for his new list locally.
>>



Well how can I return a list then, rather than a pointer to a list?

if I do this:
friend void operator=(WumpusList &, const WumpusList &);

I get the error:
'operator =(WumpusList &,const WumpusList &)' must be a member function