Reputation: 11
So I've been a little spoiled with Java/C#, and have pretty much (apparently) forgotten how to program in C++.
I have a templated doubly-linked list ("Dlist") that I've created. It's laid out in a header file (god, header files are weird), and implemented in a CPP.
So, if I remember what little C++ I know right, a fn in that CPP looks something like this:
//ctor
template <typename T>
Dlist<T>::Dlist()
{
first = NULL;
last = NULL;
return;
}//end fn
I want to create a pair of subclasses to this Dlist. In a new CPP, called, say, "stack.cpp", I have:
#include "dlist.h"
template <typename T>
class Stack : public Dlist<T>
{
public:
//template <typename T>
void add(T *o) //these are virtual fns in dlist
{
//will call push
}
//template <typename T>
T * remove() //these are virtual fns in dlist
{
//will call pop
}
//template <typename T>
Stack()
{
//i have NO idea what to put in here
}
};//end class
But when I have the line
Stack <double> stack;
in my int main(), Visual Studio FLIPS OUT.
error C2062: type 'double' unexpected
error C2065: 'Stack' : undeclared identifier
So: how do I properly create, and call, subclasses of a templated class?
I am not allowed to use the cstdlib for my stuff. Yay homework!
Upvotes: 1
Views: 197
Reputation: 1977
Actually you don't need the template on remove function. Try removing it. Also, when working with templated classes, you'll most likely to implement most functions directly into the header, so compiler will know how to generate the method depending on the type you pass.
Here's the code:
Dlist:
template<typename T>
class Dlist
{
private:
T* first;
T* last;
public:
Dlist()
{
this->first = NULL;
this->last = NULL;
}
T* remove()
{
return NULL;
}
void add(T* obj)
{
// add algorithm
}
};
Stack:
template<typename T>
class Stack : protected Dlist<T>
{
public:
Stack()
: Dlist<T>() // if you need to call constructor code from the base
{
}
void push(T* obj)
{
this->add(obj);
}
T* pop()
{
return this->remove();
}
};
Declaration:
Stack<double> stack;
Note at this line:
class Stack : protected Dlist<T>
Its protected because if you want a stack, and inherits Dlist as public, you'll still have a Dlist with Stack functions.
Upvotes: 1