'Cannot get access to a struct that was defined in a base class

I implemented BinaryTree class and inside the definition of BinaryTree I defined the structure "BinaryNode".

#ifndef BINARYTREE_H
#define BINARYTREE_H
#include <iostream>
#define SPACE 10

template <class T,class U>
class BinaryTree
{
protected:

    typedef struct BinaryNode{
        U data;
        T key;
        struct BinaryNode* left;
        struct BinaryNode* right;
        struct BinaryNode* parent;
        BinaryNode(const T _key, const U& _data): key(_key), data(_data){}
        virtual ~BinaryNode(){
        if(left)
            delete left;
        if(right)
            delete right;
        }

    }BinaryNode;
    BinaryNode* root;

Now, I want to implement another sort of BinaryTree, which is a Heap. So I want to inherit from BinaryTree and add one field, this field is a pointer of type BinaryNode, which points the last leaf in the heap (heaps are complete trees, so that if the last level is not full, the last leaf is the leaf in the right tip).

#ifndef HEAP_H
#define HEAP_H
#include "BinaryTree.h"


template <class T,class U>
class Heap : public BinaryTree<T,U>
{
public:
//|--------------------- Constructors ----------------------|
    Heap() : lastLeaf(NULL) {}

//|-------------------- Private fields ---------------------|
private:
    BinaryNode* lastLeaf;
    

When I try to compile I get this error:

error: 'BinaryNode' does not name a type; did you mean 'BinaryTree'?|

Now if I try instead:

struct BinaryNode* lastLeaf;

In addition, everywhere I use BinaryNode* in the program, I get the error:

error: 'BinaryNode' has not been declared

So its not just in the field definition.

What can I do?



Solution 1:[1]

You derived class doesn't know what template parameters to apply to BinaryNode. Therefore, you need:

template <class T,class U>
class Heap : public BinaryTree<T,U>
{
    // ...
    typename BinaryTree<T,U>::BinaryNode* lastLeaf;
};

Live demo


As per @AdrianMole's comment, clang needs the typename keyword here, so I have added that to my answer. And you don't need to use typedef, please see updated demo.

Solution 2:[2]

Adding this line:

typedef struct BinaryTree<T,U>::BinaryNode BinaryNode;

to the beggining of the file solved it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 DirichletIsaPartyPooper