1

I tried to make an Array template class but when I try to build the compiler fails to link the constructor and the method and I get :

undefined reference to `Array::Array()

undefined reference to `Array::getSize()

Here is the header file:

#pragma once

template<typename type, int length>

struct Array{
public:
    Array();
    int getSize();

private:
    type data[length];
    int m_length;
};

The Array.cpp file:

#include "Array.h"

template<typename t, int l>
Array<t, l>::Array()
{
    m_length = l;
}

template<typename type, int length>
Array<type, length>::getSize()
{
    return m_length;
}

And the main function:

#define LOG(x) cout<<x<<endl
int main()
{
    Array<int, 10> array;
    LOG(array.getSize());
}

If someone has any idea about why I am getting this, I would really appreciate.

EddieBreeg
  • 11
  • 1
  • 2
    Does this answer your question? [Why can templates only be implemented in the header file?](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – ChrisMM Jan 27 '20 at 15:56
  • Also don't forget the `int` return type on your `getSize()` implementation (though the real problem is in Chris's link) – scohe001 Jan 27 '20 at 15:57

1 Answers1

0

You need to either put your implementation into the header files, or define the usage (instantiation of the template arguments) in the source file

mutableVoid
  • 1,284
  • 2
  • 11
  • 29