khurram usman
khurram usman

Reputation: 1

copy constructor of a linked list class

i have a linked list class List. i have to make a copy constructor for it. i am actually having problem with the syntax. here is my code:

template <class T>
List<T>::List(const List<T>& otherList)
{
}

otherList is another item of type List. infact i think it is a pointer to a List. i have a getHead() function defined for class List and its works fine. i thought doing the following will be ok:

Node* temp = otherList->getHead();

node is the pointer of which the List is composed. this is a separate class Node. but doing the above gives the error:

base operand of -> has non-pointer type const List<int> 

so i tried using "." instead of "->" in the above expression. got the following error:

passing const List<int> as this argument of ListItem<T>* List<T>::getHead() [with T = int] discards qualifiers [-fpermissive]

my getHead function:

template <class T>
node<T>* List<T>::getHead()
{
return head;
}

kindly guide me

Upvotes: 0

Views: 504

Answers (2)

Ferenc Deak
Ferenc Deak

Reputation: 35408

I have the feeling that getHead() should be declared a const function... Try it and let us know if it works or not.

Upvotes: 0

Joseph Mansfield
Joseph Mansfield

Reputation: 110658

First of all, otherList is not a pointer, it's a "reference to const List<T>". We know it's a reference because of the & in its type. If it were a pointer, it would have a * in its type. A reference behaves exactly as if you just had the object itself. So using . to access its member function getHead is correct.

Now the problem is that you have a const reference, but you're calling a non-const member function. As far as the compiler is concerned, your getHead function might modify the List and so shouldn't be called on a const List. You need to declare getHead as being const. Wherever you have the declaration of getHead, stick a const before the { that begins the function:

template <typename T>
const Node<T>* List<T>::getHead() const {
  // ...
}

This assumes that getHead doesn't actually modify the list (which it shouldn't). If it does, then you can't make it a const member function and can't call it from your copy constructor because the otherList is const. However, your copy constructor should never modify the object it is copying, so your otherList should be const.

Upvotes: 2

Related Questions