views:

88

answers:

1

I am trying to return a new copy of the data in a C++ Template class. The following code is getting this error: invalid conversion from ‘int*’ to ‘int’. If I remove the new T then I am not returning a copy of the data but a pointer to it.

template<class T>
T OrderedList<T>::get( int k )
{
    Node<T>* n = list;
    for( int i = 0; i < k; i++ )
    {
        n=n->get_link();
    }
    return new T( n->get_data() ); // This line is getting the error **********
}
+10  A: 

new creates and returns a pointer. You just want a copy which will be created implicitly, since the return statement will invoke the copy constructor (or equivalent for POD) of the object T:

return n->get_data();
Konrad Rudolph
Or, depending on the definition of `Node<>` and `T`, `return T( n->get_data() )`. (Although I agree that it is unlikely given this code.)
sbi