I have 3 C++ files: genericStack.h:
template <class T>
class Stack{
public:
Stack (int size){
top = -1;
MAX_SIZE = size;
v = new T (size);
}
~Stack(){ delete v;}
T pop();
void push (T);
class Underflow{};
class Overflow{};
private:
int top;
int MAX_SIZE;
T* v;
};
genericStackImpl.c++:
#include "genericStack.h"
template <class T>
void Stack <T> :: push (T c){
if (top == MAX_SIZE - 1) throw Overflow();
v[++top] = c;
}
template <class T>
T Stack <T> :: pop(){
if (top < 0) throw Underflow();
return v[top--];
}
driver.c++:
#include <iostream>
#include "genericStack.h"
int main(){
Stack<char> sc(3);
try{
while (true) sc.push ('p');
}
catch (Stack<char>::Overflow){std::cout << "Overflow caught\n";}
try{
while (true) std::cout << sc.pop() << '\n';
}
catch (Stack<char>::Underflow){ std::cout << "Underflow caught\n";}
return 0;
}
When i compile using g++ 4.5:
g++ -o driver driver.c++ genericStackImpl.c++
I get these errors:
/tmp/ccLXRXgF.o: In function `main':
driver.c++:(.text+0x2e): undefined reference to `Stack<char>::push(char)'
driver.c++:(.text+0x3c): undefined reference to `Stack<char>::pop()'
collect2: ld returned 1 exit status
I dont understand what the problem is. If i move the implementation in the driver file, then it compiles and runs.