Strange operator= bahaviour

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;
}
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
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.
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.
WARNING:

 
ShipLoad::ShipLoad(ShipLoad &obj)


is not a copy constructor.

Are you sure? My book says it should look just like that...
110%
So what should it look like?
ShipLoad::ShipLoad(const ShipLoad &obj)
Topic archived. No new replies allowed.