0

I do not know why it crashes when I create class Vector. Please Help. In this program I want to add any type of elements into an array. I use eclipse with Cross gcc, Ubuntu

template<typename T>
class Vector{
    public:
        Vector();
        void add(const T&);
    private:
        T *elem;
        int cap;
        int len;
};

template<typename T>
Vector<T>::Vector(){
    len = 0;
    cap = 30;
    elem = new T[cap];
}

template<typename T>
void Vector<T>::(const T& m){
    elem[len] = m;
    len ++;
}

// Here I create Vector v, if I put Vector<int> v() I don't get error
Vector<int> v; //error "undefined reference to `Vector<int>::Vector()"
v.add(21); //error
Kyle A
  • 928
  • 7
  • 17
paulc
  • 125
  • 6
  • 1
    Please provide a [mcve]. – Barry Mar 24 '16 at 22:25
  • @Brian It is very funny that you do not use "very interesting features". I can not even imagine this.:) – Vlad from Moscow Mar 24 '16 at 22:45
  • The compiler needs visibility of the template definitions (both the `Vector` class AND its member functions) at the point where you intend to use `Vector`. Separate compilation and templates do not play together well. Place the definition of member functions in the header that declares the class, and make sure you `#include` that header in code which needs to use the `Vector` template. [This isn't a complete answer]. – Peter Mar 24 '16 at 23:43
  • "i don't get error" - you certainly would get error if you still had `v.add(21)` following – M.M Mar 26 '16 at 13:07

1 Answers1

1

You need to place member function definitions (including constructor definitions) in the same header where the template class is defined.

As for this statement

// here i create Vector v, if i put Vector<int> v() i don't get error
Vector<int> v();

then it is a function declaration that has return type Vector<int> and does not have parameters. It is not a definition of an object of type Vector<int>.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335