Lincoln Oh
Lincoln Oh

Reputation: 13

I have an error with unused variable warning

I have an warning in my copy constructor.

Basically I had an error in copy assignment and I solved it, but then a warning (which is treated as an error) pops up in my copy constructor.

IntList::IntList(const IntList& cpy){
  head = 0; 
  tail = 0;
  for(IntNode* i = cpy.head; i != 0; i = i->next){
    push_back(i->data);
  }
  IntList* obj1;
  IntList* obj2 = obj1;
}

IntList& IntList::operator=(const IntList& rhs){
  head = 0;
  tail = 0;
  for(IntNode* i = rhs.head; i != 0; i = i -> next){
    push_back(i->data);
  }
  IntList* obj1;
  IntList* obj2 = obj1;
  return *obj2;
}

I think it's used, because i assigned obj2 with obj1(but why is it regarded to be unused???)

i tried this but still not being solved

IntList* obj1;
IntList* obj2;
obj2 = obj1;

Upvotes: 1

Views: 368

Answers (3)

Vivek
Vivek

Reputation: 330

You should replace the two lines containing obj1 and obj2 in the assignment operator function with return *this;. The two lines containing obj1 and obj2 are not needed in the copy constructor.

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

These statements

IntList* obj1;
IntList* obj2 = obj1;

do not make any sense. Remove them.

Take into account that the copy assignment operator

IntList& IntList::operator=(const IntList& rhs){
  head = 0;
  tail = 0;
  for(IntNode* i = rhs.head; i != 0; i = i -> next){
    push_back(i->data);
  }
  IntList* obj1;
  IntList* obj2 = obj1;
  return *obj2;
}

is invalid. It does not free all previously allocated memory for the list. And it shall return reference to it self. So the last statement shall be

return *this;

The operator can look the following way

IntList & IntList::operator =( const IntList &rhs )
{
    while ( head )
    {
        IntNode *tmp = head;
        head = head->next;
        delete tmp;
    }

    tail = head;

    for ( IntNode* i = rhs.head; i != 0; i = i -> next )
    {
        push_back( i->data );
    }

    return *this;
}

Upvotes: 1

Momin Zahid
Momin Zahid

Reputation: 406

The following has no use in the code. It is pointless.

IntList* obj1; 
IntList* obj2 = obj1;

Also, it looks to be that you're copying the list but you're not actually assigning the head node to some pointer. So when the function is over, you lose the copied list.

Upvotes: 0

Related Questions