Undefined reference to constructor, using generics

I can't get it to work, but I don't see what I'm doing differently from the examples given in my textbook. Can anyone explain?

set.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#ifndef SET_H
#define	SET_H
#include <vector>
using std::vector;
template<class T>
class Set
{
public:
      Set();
      void add(T newItem);
      int getSize();
      T* getArray();                
private:
      vector<T> data;
};

template <class T>
Set<T>::Set<T>()
{
    data = new vector <T>;
}

template <class T>
void Set<T>::add(T newItem)
{
    data.push_back(newItem);
}

template <class T>
int Set<T>::getSize()
{
    return data.size();
}

template <class T>
T* Set<T>::getArray()
{
    return data;
}
#endif	/* SET_H */ 


main.cpp
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <cstdlib>
#include <string>
#include "set.h"
using namespace std;
int main()
{
 Set<int> s1;
 Set<string> s2;
 return 0;
}
Line 14 should be vector<T>* data;

Tried in Visual Studio 2010, got warning C4812: obsolete declaration style: please use 'Set<T>::Set' instead

Try changing line 18 to Set<T>::Set()
I would leave line 14 alone and remove line 20, so your constructor is just (picking up Branflake's declaration style correction)

1
2
3
4
template <class T>
Set<T>::Set()
{
}


This will leave the Set constructor to call the vector's default constructor automatically.

You will also have to correct getArray() to

1
2
3
4
5
template <class T>
T* Set<T>::getArray()
{
    return &data[0]; // get address of first element
}


If you do decide to use new to create your vector (which is a bit pointless: vector does new itself, internally for you. You usually use vector to avoid the dangers of new/delete!), then all your other methods will have to change a bit, too.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
template <class T>
void Set<T>::add(T newItem)
{
    data->push_back(newItem); // call via pointer
}

template <class T>
int Set<T>::getSize()
{
    return data->size(); // call via pointer
}

template <class T>
T* Set<T>::getArray()
{
    return &data->at(0); // etc
    // As I mentioned about, this was wrong anyway: you need to get the
    // address of the first element. For a normal vector variable, you can
    // use &data[0];.  But calling operator[] through a pointer uses slightly
    // painful syntax: &(*data)[0]; or &data->operator[](0);
}
Last edited on
Thanks for the help, guys.
Topic archived. No new replies allowed.