Ole-M
Ole-M

Reputation: 821

Undefined reference to constructor

I'm a Java developer experimenting with C++.

I just created a new class. In my other class I want to have list where I can store Filter objects.

Filter.h

#ifndef FILTER_H_
#define FILTER_H_

class Filter {
public:
  Filter(int id);
  int id;
  ~Filter();

};

#endif /* FILTER_H_ */

Filter.cpp

#include "Filter.h"

Filter::Filter(int id) {
this.id = id;
}
Filter::~Filter() {
}

Cars.h

#include "Filter.h"
...
...
private:
  std::vector<Filter> filters;

Cars.cpp

so in a function here I try to do this:

int id = 2;
Filter *filter = new Filter(id);

which generate this error:

Cars.cpp:120: undefined reference to `Filter::Filter(int)'
stl_construct.h:83: undefined reference to `Filter::~Filter()'

What's the reason for this?

Upvotes: 10

Views: 40768

Answers (1)

Lyubomir Vasilev
Lyubomir Vasilev

Reputation: 3030

The error is generated by the linker because it can not see where the definition of the constructor is located.

If you are using an IDE, you should add both .cpp files to the project so that they can be compiled together and the definition would be found by the linker.

If not, then you have to combine them yourself -assuming you are using gcc:

g++ cars.cpp filter.cpp

will combine them into one executable and should not show you that error

Upvotes: 26

Related Questions