0

I'm new to programming and I'm trying to implement a simple version of an ArrayList. I'm getting an error, and when I tried to find a solution, people said it was because a constructor was declared but not implemented. I implemented all the constructors I declared in the header, so I'm not sure what's wrong. Some advice appreciated!

Error 1 error LNK2019: unresolved external symbol "public: __thiscall ArrayList::ArrayList(void)" (??0?$ArrayList@H@@QAE@XZ) referenced in function _main

Error 2 error LNK2019: unresolved external symbol "public: void __thiscall ArrayList::add(int)" (?add@?$ArrayList@H@@QAEXH@Z) referenced in function _main

Error 3 error LNK1120: 2 unresolved externals

ArrayList.h

#pragma once
#ifndef ArrayList_h
#define ArrayList_h
#include <stdexcept>
using namespace std;

template <class T>
class ArrayList
{
public:
    ArrayList();
    ~ArrayList();
    void add(T item);
    void expandArray();
    T get(int index);

private:
    int size;
    int length;
    T* list;
};

#endif

//ArrayList.cpp
#include "ArrayList.h"

template <class T>
ArrayList<T>::ArrayList(){
    size=1;
    length=0;
    list = new T(size);
    for(int x=0; x<size;x++){
        list[x]=NULL;
    }

}

template <class T>
ArrayList<T>::~ArrayList(){
    delete[] list;
}


template <class T>
void ArrayList<T>::add(T item){
    if(length>=size){
        expandArray();
    }
    list[length]=item;
    length++;
}

template <class T>
void ArrayList<T>::expandArray(){
    size*=2;
    T* temp = new T(size);
    for(int x=0;x<size;x++){
        temp[x]=NULL;
    }
    for(int x=0;x<length;x++){
        temp[x]=list[x];
    }
    delete[] list;
    list=temp;
}

template <class T>
T ArrayList<T>::get(int index){
    if(index>length||index<0){
        throw out_of_range("Index out of bounds!");
    }
    return list[index];
}

Main.cpp

#include "ArrayList.h"


int main(){

    ArrayList<int>* list = new ArrayList<int>();

    for(int x=0; x<=30;x++){
        list->add(x);
    }

    return 0;
}
Protomen
  • 9,471
  • 9
  • 57
  • 124

1 Answers1

4

Template definitions need to be in the header file. Move your ArrayList<T>::ArrayList constructor definition into ArrayList.h.

Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132
  • I'm sorry, I'm still relatively new to c++ and headers. Do I just move the entire implementation of ArrayList::ArrayList into the header? I thought headers were supposed to be used for declarations only. – user3272701 Feb 13 '14 at 20:09
  • @user3272701 The entirety of a template class needs to be in the header. For non-template classes, you'd be correct. – KitsuneYMG Feb 13 '14 at 20:10
  • ...or use explicit template instantiation but I think that would just confuse the whole situation so I'm gonna go sit in the corner and eat some pie. – Captain Obvlious Feb 13 '14 at 20:10
  • There are [similar questions](http://stackoverflow.com/questions/21488744/how-to-defined-constructor-outside-of-template-class?rq=1) – codah Feb 13 '14 at 20:21