mercredi 24 avril 2019

Why does my compiler make me add the "this->" pointer to access parent variables from a child class

I'm coding a simple LinkedList class that is a child class to an abstract List class. After finishing the List class I started to code the LinkedList class, and I noticed that the compiler would not let me access the protected variables from the members of the List class directly, even though LinkedList is a child class of List. When I do not add the "this->" pointer before one of List's variables, I get an error that says the variable is not declared in the scope. I'm sure there is a simple explanation for this, but I can't figure out why the two protected variables in my List class and its members are not accessible from the members of the LinkedList class.

List:

template<typename T>
class List {
    protected:
        unsigned int numElements;
        Node<T>* head;
    public:
        List();
        ~List();
        virtual void append(T x) = 0;
        virtual T remove() = 0;
        virtual bool isEmpty();
};

template<typename T>
List<T>::List() {
    numElements = 0;
    head = NULL;
}

template<typename T>
List<T>::~List() {
    while(NULL != head) {
        Node<T>* newHead = head->getNext();
        delete head;
        head = newHead;
    }
}

template<typename T>
bool List<T>::isEmpty() {
    if (numElements)
        return false;
    return true;
}

LinkedList with one member example:

template<typename T>
class LinkedList: public List<T> {
    public:
        void append(T x);
        T remove();
        void append_tail(T x);
        void insert(T x, int pos);
        T remove_at(int pos);
        void print();
        int getNumElements();
};

template<typename T>
void LinkedList<T>::append(T x) {
    // create a new node with its next as the head
    Node<T>* appendNode = new Node<T>(x, this->head);
    // set the head to this new node
    this->head = appendNode;
    this->numElements++;
}

Node class that is included (not very relevant)

#ifndef NODE_H
#define NODE_H

template<typename T>
class Node {
    private:
        T value;
        Node * next;
    public:

        Node(T v, Node * n);
        T getValue() const;
        Node * getNext() const;
        void setNext(Node * p);
};


template<typename T>
Node<T>::Node(T v, Node * n) {
    value = v;
    next = n;
}


template<typename T>
T Node<T>::getValue() const {
    return value;
}


template<typename T>
Node<T>* Node<T>::getNext() const {
    return next;
}

template<typename T>
void Node<T>::setNext(Node * n) {
    this->next = n;
}

#endif


Aucun commentaire:

Enregistrer un commentaire