Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined reference to constructor

Tags:

c++

g++

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?

like image 474
Ole-M Avatar asked Aug 03 '12 08:08

Ole-M


1 Answers

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. It 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

like image 148
Lyubomir Vasilev Avatar answered Sep 19 '22 10:09

Lyubomir Vasilev