user3222060
user3222060

Reputation: 37

Undefined reference classes?

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

Answers (2)

David Grayson
David Grayson

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:

  1. Remove the line right after "public:" that declares the constructor. If you don't declare any constructors, your object will just use a default constructor supplied by the compiler which might be good enough.
  2. Or, add a definition for the constructor somewhere in your program.
  3. Or, you can change the line that declares 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

R Sahu
R Sahu

Reputation: 206567

Why is it giving me an undefined reference to MySet::MySet() while trying to print my vector?

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

Related Questions