Strange operator= bahaviour
Mar 3, 2010 at 8:07pm UTC
I'm doing an assignement where I'm writing copy constructors and operator= constructors to copy objects with pointers in them. Every time an object is copied a variable named size should increase with 1.
So, when i copy to an object that is also created at the same time, the copy constructor is invoced, as it should. But when i copy to an existing object, both copy constructor and = constructor is invoked. Have I made an error in the design of the constructors?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
ShipLoad::ShipLoad(ShipLoad &obj)
{
size = obj.size + 1;
nrOfWords = obj.nrOfWords;
words = new string[size];
cout << "\nCopy constructor, size=" << size << endl;
for (int i = 0; i < size - 1; i++)
words[i] = obj.words[i];
words[size - 1] = "" ;
}
ShipLoad ShipLoad::operator =(const ShipLoad &right)
{
if (size > 0)
delete [] words;
size = right.size + 1;
nrOfWords = right.nrOfWords;
words = new string[size];
cout << "\noperator=, size=" << size << endl;
for (int i = 0; i < size - 1; i++)
words[i] = right.words[i];
words[size - 1] = "" ;
return *this ;
}
Mar 3, 2010 at 8:13pm UTC
at teh start of operator= try:
1 2 3
if (&right == this )
return *this ;
Also should be this:
1 2
ShipLoad& ShipLoad::operator =(const ShipLoad &right)
in reference to 'this' members you should probably use the this keyword, followed by arrow operator to point to the member.
ie:
1 2 3 4 5 6
function(class & obj)
{
this ->number = obj.number;
}
private :
int number;
Last edited on Mar 3, 2010 at 8:18pm UTC
Mar 3, 2010 at 8:44pm UTC
Line 12 is the problem, as gcampton said. That should be returning a reference, not a copy of the object.
gcampton wrote:in reference to 'this' members you should probably use the this keyword, followed by arrow operator to point to the member.
I strongly disagree. I always found that redundant, cluttering, and silly.
Mar 3, 2010 at 8:54pm UTC
That should be returning a reference, not a copy of the object.
When you say it like that it's pretty obvious.
Thanks both of you.
Mar 3, 2010 at 9:22pm UTC
WARNING:
ShipLoad::ShipLoad(ShipLoad &obj)
is not a copy constructor.
Mar 3, 2010 at 9:26pm UTC
Are you sure? My book says it should look just like that...
Mar 3, 2010 at 9:27pm UTC
110%
Mar 3, 2010 at 9:28pm UTC
So what should it look like?
Mar 3, 2010 at 9:54pm UTC
ShipLoad::ShipLoad(const ShipLoad &obj)
Topic archived. No new replies allowed.