1

I have a function that creates a vector, then calls a class constructor with that vector as an input, but it returns with an error saying

undefined reference to Class::Class(std::vector<double, std::allocator<double> >)

The class has a constructor for a

std::vector<double>

but not a

std::vector<double, std::allocator<double> >

Some example code:

std::vector<double> x1;
std::vector<double> x2;
std::vector<double> myvec;
double thisX;

for (int i=0; i<x1.size(); i++ {
    thisX = x1[i];
    myvec.push_back(thisX);
}
for (int i=0; i<x2.size(); i++ {
    thisX = x2[i];
    myvec.push_back(thisX);
}

Class MyClass( myvec );
// has a constructor for std::vector<double>
// compiler throws the undefined reference to 
// Class::Class(std::vector<double, std::allocator<double> >)

Any insight is appreciated! I'm relatively new to C++ if it wasn't obvious.

Timmortal
  • 47
  • 1
  • 5
  • The linker did not see the definition of your constructor that takes a `std::vector`. And a `std::vector` is a *class-template* that has two template parameters. The element type, and an allocator type. the allocator is a default template parameter – WhiZTiM Jul 21 '17 at 12:39
  • 2
    take a look at some [docs](http://en.cppreference.com/w/cpp/container/vector). A vector has always a second template parameter which defaults to `std::allocator` – 463035818_is_not_an_ai Jul 21 '17 at 12:39
  • Where do you defined the constructor? – NathanOliver Jul 21 '17 at 12:43
  • 2
    Those two are the same type, so your class can't have a constructor for `vector`. The "undefined reference" indicates that you have declared one, but that it doesn't have an implementation. The two most common reasons for a missing implementation are 1) forgetting to write one, and 2) forgetting to link with it. – molbdnilo Jul 21 '17 at 12:45

1 Answers1

3

std::vector<double> is the short form of std::vector<double, std::allocator<double> >, because the second template argument of std::vector<> defaults to std::allocator<T>.

The cause of the error is different.


undefined reference to Class::Class error means that there is a declaration of this constructor but no definition.

You probably do not link the object file or library with the definition of Class::Class. It needs to be linked to resolve that undefined reference.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
  • What if the class is defined in a `.h` file that lies in the same directory of my `.cpp` program? – Rodrigo May 17 '20 at 19:32