Adam G
Adam G

Reputation: 165

Why am I getting "invalid conversion from const pointer to pointer?

I'm working with a linked list, specifically I am trying to append an object. The append function is passed a pointer to the object I want to add.

This pointer is then used in the initialization of a OULink (a list node) object.

Inside my OULink class, I am trying to set the data pointer to = the object I am trying to add, and that is where I am getting an error:

error: invalid conversion from 'const NvraRecord*' to 'NvraRecord*' [-fpermissive] this->data = item;

I thought since they were both of type T* I could assign one to the other.

template <typename T>
class OULinkedList {
    template <typename F>
    friend class OULinkedListEnumerator;
private:
    Comparator<T>* comparator = NULL;               // used to determine list order and item equality
    unsigned long size = 0;                         // actual number of items currently in list
    OULink<T>* first = NULL;                        // pointer to first link in list
    OULink<T>* last = NULL;                         // pointer to last link in list
public:
    OULinkedList(Comparator<T>* comparator);        // creates empty linked list with comparator
    virtual ~OULinkedList();                        // deletes all links and 
template <typename T>
bool OULinkedList<T>::append(const T* item) {


    if(this->first == NULL){

        OULink<NvraRecord> currentNode(item);
        this->first = &currentNode;

    }else{

    }
    std::cout << *this->first->data << std::endl;
    return false;
}



template <typename T>
class OULink {
    template <typename F>
    friend class OULinkedList;
    template <typename F>
    friend class OULinkedListEnumerator;
private:
    T* data = NULL;                                     // pointer to data item of any type
    OULink* next = NULL;                                // pointer to next link
public:
    OULink(const T* item);
    virtual ~OULink();
};

template<typename T>
OULink<T>::~OULink(){

}
// Implementation goes here
template<typename T>
OULink<T>::OULink(const T* item){

    this->data = item;
}

Upvotes: 0

Views: 1111

Answers (1)

0x5453
0x5453

Reputation: 13589

The OULink constructor takes a const T* item, which is a pointer to a const T. OULink.data can store a T*, which is a pointer to a non-const T.

You cannot assign a const T* to a T*, because the const is a contract that says "I will not let the object I am pointing to change." If you could assign to a T*, that pointer would allow the object to be modified, which would break that contract.

You probably want to change the constructor OULink(const T* item); to OULink(T* item);.

Upvotes: 1

Related Questions