0

I'm trying to create a new object of the class Queue<T>, with the following:

Queue<char[40]> *q = new Queue<char[40]>(100);

Then, I want to use this q on another class constructor:

Interface<char[40]> i(q);

If I just use it, I get an error saying invalid conversion from ‘Queue<char [40]>*’ to ‘int’, which I figure means I'm trying to pass the value of q, which is the pointer to it instead of the actual value. Fine. Then I redefined the Interface<T> constructor to receive a pointer instead of the value itself, so the signature is

Interface(DataStructure<T>& q);

Since Queue extends DataStructure. For some reason, now the instantiation of q fails:

undefined reference to `Queue<char [40]>::Queue(int)

But I am quite sure I have written the constructor method WITH an INT parameter

template<typename T>
Queue<T>::Queue(int size): DataStructure<T>(size) {
    std::cout << size << std::endl;
}

Why the hell am I getting this error, then? To play with pointers is just getting a mess and I could not figure out by any means what to do now.

ranieri
  • 2,030
  • 2
  • 21
  • 39
  • 5
    "undefined reference" seems to suggest you defined the constructor in a source file rather than in the header.. http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file – dyp Apr 03 '14 at 22:53
  • On another note: this `char[40]` looks a bit suspicious. Perhaps you want to use `std::string` instead? – Danvil Apr 03 '14 at 23:15
  • @dyp this constructor is defined in the header as `Queue(int size);` – ranieri Apr 04 '14 at 20:54
  • Does that mean that you *did* define (= the block shown in your question; the definition of a function contains the function body `{ /*...*/ }`) it in the source file? This does not work for member functions of class templates. Please read the Q&A I've linked above. – dyp Apr 04 '14 at 20:55
  • @dyp okay, now it works. One more question: to use a template with `char[40]`, do I have to use pointers everywhere? If I want to return the value of something in a function, it complains I'm returning an array. – ranieri Apr 04 '14 at 21:37
  • That's the trouble with array types. Please don't use pointers (this can easily lead to other problems). Rather, put the arrays inside class/struct types; you can also use `std::array` which does exactly that. – dyp Apr 04 '14 at 21:40

1 Answers1

3

This code Queue<T>::Queue(int size) suggests you put the definition in a source file. If you use templates all your code must be in the header file. (There are other approaches, but this is the easiest).

Danvil
  • 22,240
  • 19
  • 65
  • 88