I have created a separate class in a separate file ("stack.cpp") to help me with using a stack for my main program that evaluates postfix equations. I want to use a templated stack but I am not sure if I can make quick changes to this code to do so or if I have to start over. I also want to know if I need to change the file type.
My 3 questions:
1:
Is it possible to convert the code below to a templated stack?
2:
If question 1 is yes, it is reasonable?
3:
When creating a templated stack, do you have to save as a header file?
You don't actually *have* to define a templated class or function in a header.
If you only plan to use the stack in one .cpp file, you can just declare it at the head of the file. But you do need to use a header if you want to use the same templated class or function in different cpp files.
The rule is that the compiler must see the whole definition of a templated class or function before it is used in a cpp file (there's no such thing as a forward definition in this case)
Andy
PS In theory you could cut and paste the stack into the top of every cpp file, but that would not be a smart move as it would make maintenance, etc. more difficult.
PPS It would be better if made your data members private.
> I think that making your array in the constructor solves a few errors that you're likely to encounter instead of defining it in the class definition.
I disagree. It solves nothing, but now you need to code a destructor, a copy constructor and an assignment operator.
The only problem that you may have is if T has not default constructor. In which case you ought to use allocators (placement new).
But if you are going to do that, you could simply use std::stack
> PS In theory you could cut and paste the stack into the top of every cpp file
that's what an #include does
The alternative is to use explicit instantiation.