2

I'm trying to make a Binary Search Tree class that inherits from a Tree class but the compiler says that the data members of the Tree class aren't inherited in the BST class.

Tree.h

template <class T>
class Tree {
protected:
    class Node {
    public:
        T value;
        Node * left;
        Node * right;
    };
    Node * root;
public:
    Tree() : root(NULL) { }
};

BST.h

template <class T>
class SearchTree : public Tree<T> {
public:
    void foo();
};

template <class T>
void SearchTree<T>::foo() {
    Node * node = NULL;    //error- Unknown type name 'Node'
    root = node;    //error- Use of undeclared identifier 'root'
}

I expect to be able to access Node and root from the base class "Tree". Why is the compiler saying they are undeclared and unknown?

Evg
  • 25,259
  • 5
  • 41
  • 83
Ezra Dweck
  • 29
  • 2

1 Answers1

5

When the base class depends on a template parameter, its scope is not examined [temp.dep/4]:

In the definition of a class or class template, the scope of a dependent base class is not examined during unqualified name lookup either at the point of definition of the class template or member or during an instantiation of the class template or member.

Use this-> to refer to base class data members and Tree<T>:: to refer to member types:

template<class T>
void SearchTree<T>::foo() {
    typename Tree<T>::Node * node = NULL;
    this->root = node;
}

Tree<T>::Node is a dependent type, so it should be prefixed with the typename keyword.

Alternatively, you can introduce names with using declaration:

template<class T>
class SearchTree : public Tree<T> {
public:
    void foo();

protected:
    using typename Tree<T>::Node;
    using Tree<T>::root;
};
Evg
  • 25,259
  • 5
  • 41
  • 83