Reputation: 1166
I have defined a struct within the protected section of a parent class, which I would like to use in an inherited class.
This works as expected if the parent/child classes aren't templated classes. But does not compile as-is below.
Specifically, the compiler (clang 8.0.1) reports:
inheritance_example.cpp:33:26: error: unknown type name 'Node'
this->head = new Node(toAdd);
From what I have read, I am guessing that the template type specification isn't being assigned to Node
, and is thus not being found by the inherited class, but trying the fixes I have found in that vein (i.e. add something along the lines of using Parent<T>::Node
, or add a type specifier to the call to the Node constructor), have not worked for me.
Any ideas on how to fix this issue?
#include<iostream>
template <class T>
class Parent
{
protected:
struct Node
{
Node(int value)
{
this->data = value;
this->next = nullptr;
};
~Node() {};
Node* next;
int data;
};
Node* head;
public:
Parent() {};
~Parent() {};
};
template <class T>
class Child : Parent<T>
{
public:
Child()
{
this->head = nullptr;
};
~Child()
{
delete this->head;
this->head = nullptr;
};
void dummyAdd(T toAdd) {
this->head = new Node(toAdd);
};
void dummyPrint()
{
std::cout << this->head->data << std::endl;
};
};
int main()
{
Child<int> t;
t.dummyAdd(5);
t.dummyPrint();
return 0;
}
Upvotes: 1
Views: 273
Reputation: 32847
In order to pack the comment into an answer!
Node
is a depended name and hence you need to use keyword typename
there. Meaning in the dummyAdd
function, you need
void dummyAdd(T toAdd)
{
this->head = new typename Parent<T>::Node(toAdd);
// ^^^^^^^^^^^^^^^^^^^^
};
That is, however, a bit verbose/ more typing. Therefore providing a type alias for Node
in the Child
will be a good idea.
template <class T>
class Child : Parent<T>
{
using Node = typename Parent<T>::Node; // template type alias
public:
void dummyAdd(T toAdd)
{
this->head = new Node(toAdd); // now you can this
};
// other code...
};
Upvotes: 2