0

I am new to C++. I am writing a simple Dynamic Array class. When I am trying to compile the code with the command g++ DynamicArray.cpp Example.cpp then I am getting the following linking error:

/usr/bin/ld: /tmp/ccUXQrPz.o: in function `main':
Example.cpp:(.text+0x4b): undefined reference to `DynamicArray<int>::pushBack(int)'
/usr/bin/ld: Example.cpp:(.text+0x6f): undefined reference to 
`DynamicArray<int>::at(unsigned int)'
collect2: error: ld returned 1 exit status

My Code:
Example.cpp:

#include "DynamicArray.h"
#include <iostream>
using namespace std;
int main() {
   DynamicArray<int> arr;
   for(auto i = 0; i < 5; ++i)
       arr.pushBack(i);
   for(int i = 0; i < 5; i++)
       cout << arr.at(i) << " ";
   return 0;
}

DynamicArray.h:

#ifndef DYNAMIC_ARRAY
#define DYNAMIC_ARRAY

template<typename T>
class DynamicArray {
public:
    void pushBack(T element);
    //void popBack();
    T at(unsigned index);
    //unsigned size();
    //unsigned capacity();
    // DynamicArray(unsigned size);
private:
    unsigned currentSize{0};
    unsigned currentCapacity{0};
    T *array{nullptr};
};

#endif

DynamicArray.cpp:

#include "DynamicArray.h"

template<typename T>
void DynamicArray<T>::pushBack(T element) {
    if(currentSize == 0) {
        ++currentCapacity;
        array = new T(1);
        array[0] = element;
    } else if(currentSize == currentCapacity) {
        currentCapacity *= 2;
        T *tempArray = new T(currentCapacity);
        for(auto i = 0; i < currentSize; ++i) {
            tempArray[i] = array[i];
        }
        delete array;
        array = tempArray;
        array[currentSize] = element;
    }
    ++currentSize;
}

template<typename T>
T DynamicArray<T>::at(unsigned index) {
    return array[index];
}

I tried to write a different example without using templates and that is working fine, Am I doing something wrong?

0 Answers0