I am using C++ and I am trying to create a templated class (a Stack).
I would like to define the copy constructor and the assignment operator.
There are defined in the header and then I implement them in the cpp file.
Here are the problems I get:
– For the copy constructor:
prototype for ‘Stack::Stack(const Stack&)’ does not match any in class ‘Stack’
– For the assignement operator:
stack.cpp:28: error: no ‘Stack& Stack::operator=(const Stack&)’ member function declared in class ‘Stack’
– For the constructor:
stack.cpp:4: error: candidate is: Stack::Stack()
Here is the header file:
// stack.hpp
#ifndef STACK_HPP
#define STACK_HPP
#include <stdio.h>
#include <assert.h>
template <class T>
class Stack
{
public:
Stack();
~Stack();
Stack(const Stack&);
Stack& operator=(const Stack&);
private:
T* v_;
size_t vsize_;
size_t vused_;
};
Here is the cpp file:
// stack.cpp
#include "stack.hpp"
template <class T>
Stack<T>::Stack() :
v_(0),
vsize_(10),
vused_(0)
{
v_ = new T[vsize_];
}
template <class T>
Stack<T>::~Stack()
{
delete[] v_;
}
// Stack(const Stack&);
template <class T> Stack<T>::Stack( const Stack<T>& other) :
v_(NewCopy(other.v, other.vsize_, other.vsize_)),
vsize_(other.vsize_),
vuser_(other.vused)
{
}
// Stack& operator=(const Stack&);
template<class T> Stack<T>& Stack<T>::operator=(const Stack<T>& other)
{
if (this != &other)
{
T* v_new = NewCopy(other.v_, other.vsize_, other.vsize__;
delvete v_;
v_ = v_new
vsize_ = other.vsize_;
vused_ = other.vused_;
}
return *this
}
One last thing, here is the log from the compilation:
g++ -c stack.cpp -o stack.o
stack.cpp:20: error: prototype for ‘Stack<T>::Stack(const Stack<T>&)’ does not match any in class ‘Stack<T>’
stack.cpp:4: error: candidate is: Stack<T>::Stack()
stack.cpp:28: error: no ‘Stack<T>& Stack<T>::operator=(const Stack<T>&)’ member function declared in class ‘Stack<T>’
I am sure this is only a small typo error but I cannot seem to find it.
Thanks for your help
You can’t compile templates into separate compilation units. In short, all the template code has to all be in one header. This is likely whats causing your problem.
The reason is that templates don’t define true classes. Templates specify how code can be generated. So when you make a
The compiler uses the template to generate a copy constructor:
This is a completely different type than a
which will define a completely independent copy constructor, and completely independent set of methods.
One option many use is to include the cpp in the header, in a reverse kind-of-way.
ie in Stack.hpp, at the bottom
but that kind of hides the fact that really its all just plopped into one header.