0

I'm making a basic array class in VS2015. It initially worked when the function code was in the header file, but now that I've moved that over to a .cpp file I get a C1004: unexpected end-of-file found for the header file.

Array.h:

    #pragma once

    template <class T> class Array
    {
    private:
        T *m_data;
        int m_length;

    public:

        Array() : m_length(0), m_data(nullptr) {}

        Array(int length) : m_length(length);

        Array(Array<T>& copyArray) : Array(copyArray.size());

        ~Array();

        void clear();

        T& at(int index);

        T& operator[](int index);

        int size();
    };

Array.cpp:

#include "Array.h"

template<typename T>
Array::Array(int length) : m_length(length)
{
    m_data = new T[m_length];
}

template<typename T>
Array::Array(Array<T>& copyArray) : Array(copyArray.size())
{
    for (int index = 0; index < copyArray.size(); ++index)
    {
        at(index) = copyArray[index];
    }
}

template<typename T>
Array::~Array()
{
    delete[] m_data;
    m_data = nullptr;
}

template<typename T>
void Array::clear()
{
    delete[] m_data;
    m_data = nullptr;
    m_length = 0;
}

template<typename T>
T& Array::at(int index)
{
    if (m_data != nullptr)
    {
        if (index < m_length && index >= 0)
        {
            return m_data[index];
        }
        throw OutOfBoundsException;
    }
    throw NullArrayException;
}

template<typename T>
T& Array::operator[](int index)
{
    if (m_data != nullptr)
    {
        if (index < m_length)
        {
            return m_data[index];
        }
        else
            throw "Out of array bounds";
    }
    else
        throw "Array is null";
}

template<typename T>
int Array::size()
{
    return m_length;
}
Ðаn
  • 10,934
  • 11
  • 59
  • 95
  • You're sure you pasted the entire header file exactly? – aschepler Apr 27 '17 at 23:38
  • 2
    Don't know if this is the cause, but `Array(int length) : m_length(length);` is not valid. Either take off the member initializer list or add a body. Same for the next constructor. – aschepler Apr 27 '17 at 23:40
  • Look carefully at your constructors in the header. They are missing braces or you need to remove the initializer list if you don't plan to implement them there. – Retired Ninja Apr 27 '17 at 23:40
  • 2
    Useful reading: [Why can templates only be implemented in the header file?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – user4581301 Apr 27 '17 at 23:41
  • Oh, I'm an idiot, haha. – Cybernaut Apr 28 '17 at 02:30

0 Answers0