I am implementing a Vector class using template in C++. Below is the code that I have written. There are two source files and a header file as shown below:
Vector.h:
template <class T>
class Vector
{
T *data;
int vSize;
int vCapacity;
public:
Vector();
~Vector();
void PushBack(const T&);
void PopBack();
int Size() const;
int Capacity() const;
void Reserve(const int&);
bool Empty() const;
T& operator[](const int&);
};
Vector.cpp:
#include "Vector.h"
///////////////////////////////////////////////////////////////////////////
template <class T>
Vector<T>::Vector(){
data = nullptr;
vSize = 0;
vCapacity = 0;
}
///////////////////////////////////////////////////////////////////////////
template <class T>
Vector<T>::~Vector(){ delete[] data; }
///////////////////////////////////////////////////////////////////////////
template <class T>
void Vector<T>::PushBack(const T& val)
{
if(vSize == vCapacity)
{
if(vCapacity == 0)
{
Reserve(1);
}
else
{
Reserve(2 * vCapacity);
}
}
data[vSize] = val;
vSize++;
}
///////////////////////////////////////////////////////////////////////////
template <class T>
void Vector<T>::PopBack()
{
vSize--;
}
///////////////////////////////////////////////////////////////////////////
template <class T>
int Vector<T>::Size() const{ return vSize; }
///////////////////////////////////////////////////////////////////////////
template <class T>
int Vector<T>::Capacity() const{ return vCapacity; }
///////////////////////////////////////////////////////////////////////////
template <class T>
void Vector<T>::Reserve(const int& newCapacity)
{
T *newData;
try
{
newData = new T[newCapacity];
}
catch(...){
cout << "Memory allocation failure...";
}
for(int i = 0; i < vSize; i++)
{
newData[i] = data[i];
}
delete[] data;
data = newData;
vCapacity = newCapacity;
}
///////////////////////////////////////////////////////////////////////////
template <class T>
bool Vector<T>::Empty() const
{
return (vSize == 0);
}
///////////////////////////////////////////////////////////////////////////
template <class T>
T& Vector<T>::operator[](const int& offset)
{
return data[offset];
}
Main.cpp:
#include "Vector.h"
int main()
{
Vector<int> v;
return 0;
}
I am getting below error.
||=== Build: Debug in CppApp (compiler: GNU GCC Compiler) ===|
obj\Debug\Main.o||In function `main':|
D:\CodeBlocks\CppApp\Main.cpp|5|undefined reference to `Vector<int>::Vector()'|
D:\CodeBlocks\CppApp\Main.cpp|18|undefined reference to `Vector<int>::~Vector()'|
||error: ld returned 1 exit status|
||=== Build failed: 3 error(s), 0 warning(s) (0 minute(s), 4 second(s)) ===|
I am unable to understand the error. Request you all to help. I have tried several other attempts to understand it, but failed to do so. Thank you :)