Lincoln Oh Lincoln Oh - 20 days ago 5
C++ Question

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;

Answer

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;
}