0

I am implementing a dynamic array in c++ using a raw pointer. I'm new to using templates. I decided to split the class into two .hpp and .cpp files also for the sake of practice. I'm getting the following compilation error in the source file when initializing the T array:

"Allocation of incomplete type 'T'"

Here is the header file:

template <class T>
class DynArray {

public:
    DynArray(); //default constructor
private:
    T * array; //internal array
    int memsize; //number of allocated memory slots
    int t_size; //number of occupied memory slots
};

Here is the source file:

template <>
DynArray<class T>::DynArray() {
    memsize = 2;
    t_size = 0;
    array = new T[memsize];

}

I'm not comfortable with what I'm doing here in the source file. I basically followed what my IDE (xcode) told me to do, but something feels wrong about creating a specialized template here. What is a correct way of doing this?

DjMrkv999
  • 1
  • 2
  • 1
    Move the constructor content to the header. Template type declarations in source files don't really "work well". – Matthias247 Mar 25 '18 at 02:41
  • 1
    Everything is correct, except it needs to be moved to the header. Well, mostly correct. You also need to change `template <> DynArray::DynArray()` to `template DynArray::DynArray()`. – Alex Huszagh Mar 25 '18 at 02:54

1 Answers1

1

Please read this as a start point Why can templates only be implemented in the header file?

Regarding the error Allocation of incomplete type 'T'. Please look carefully at the code

template <>
DynArray<class T>::DynArray()

template there does not introduce type T. The type class T is introduced in the second line, it is mentioned first time there. As you may know class T without template is a forward declaration and is an incomplete type, its size is unknown and new can not allocate memory of unknown size. The proper template class member should be declared like this

template <class T>
DynArray<T>::DynArray()

It is correct syntactically, but not practically, read the article mentioned above.

273K
  • 29,503
  • 10
  • 41
  • 64