Reputation: 37
Why is it giving me an undefined reference to MySet::MySet()
while trying to print my vector
? Any help would be much appreciated. Thanks
#include <iostream>
#include <vector>
using namespace std;
class MySet{
public:
MySet();
MySet(const vector<int> v3);
void printVector(const vector<int>& newMyVector);
};
int main()
{
vector<int> myVector;
myVector.push_back(1);
myVector.push_back(2);
MySet m;
m.printVector(myVector);
return 0;
}
void MySet::printVector(const vector<int>& newMyVector){
cout << "Vector: ";
for(unsigned int i = 0; i < newMyVector.size(); i++)
{
cout << newMyVector[i] << "|";
}
}
Upvotes: 0
Views: 90
Reputation: 87386
Your program does not include a definition for the constructor of MySet. The constructor's name is MySet::MySet()
. So when you try to create an instance of the object, the compiler does not know what to do. There are a couple solutions:
MySet::MySet()
so that it also defines it.The code for option 2 would look like this, somewhere outside the class:
MySet::MySet()
{
// do stuff here to construct object
}
The code for option 3 would look like this, somewhere inside the class:
MySet()
{
// do stuff here to construct object
}
Upvotes: 0
Reputation: 206567
Why is it giving me an undefined reference to
MySet::MySet()
while trying to print myvector
?
You are creating an instance of MySet
using
MySet m;
That uses the default constructor. The default constructor has been declared in the class but it has not been defined. You can fix it by defining it.
MySet::MySet() {}
Upvotes: 1