0

I have two class, linkedList and orderedLinkedList. The class orderedLinkedList inherits from linkedList as follows.

template<class Type>  //definition of node
struct node
{
    Type info;
    node<Type> *link;
};

template<class Type>  
class linkedList
{
protected:
    int count;          // no. of elements in the list
    node<Type> *first;  // pointer to the first node
    node<Type> *last;   // pointer to the last node

public:
    // some functions
}

template<class Type>
class orderedLinkedList: public linkedList<Type>
{
public:
    // some functions
};

To my knowledge, protected members are accessible in the class that defines them and in classes that inherit from that class. However, a compile time error pops up saying: Use of undeclared identifier 'first' in the following function.

template<class Type>
bool orderedLinkedList<Type>::search(const Type& x) const
{
    node<Type> *p;

    p = first; // <- Use of undeclared identifier 'first'
    while (p != NULL && p->info < x)   
        p = p->link;

    return (p != NULL && p->info == x);
}

I have tried making the pointer first public, and it doesn't work as well. Is there something fundamental I am not getting about inheritance? Thanks in advance.

Tony Tarng
  • 699
  • 2
  • 8
  • 17
  • Try using `this->first` to access the class member – Jimbo May 25 '16 at 15:47
  • @NathanOliver, beat me by 10 secs! – SergeyA May 25 '16 at 15:49
  • Try posting an [MVCE](http://stackoverflow.com/help/mcve) -- the code you've posted looks fine. Perhaps you accidentally declared `search` as `static` in the code you've elided? – Chris Dodd May 25 '16 at 15:51
  • @Jimbo Yes, it works. Do you mind elaborating why this is the case? – Tony Tarng May 25 '16 at 15:51
  • 1
    It's how you access member variables linked to the object instance. Without it the compiler doesn't know to look "inside" the instance of the object that the method was called on :) – Jimbo May 25 '16 at 15:53

0 Answers0