Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

undefined reference to `Class::Function() / error: Id returned 1 exit status

I’m trying to initialize value, I follow Bjarne Stroustrup‘s book but cannot run this code.

#include <iostream>

using namespace std;

struct Date
{
    int y, m, d;               // year, month, day
    Date(int y, int m, int d); // check for valid & initialize
    void add_day(int n);       // increase the Date by n days
};

int main()
{
    Date today(2021, 1, 6);

    return 0;
}

Here is the error:

undefined reference to `Date::Date(int, int, int)'
collect2.exe: error: ld returned 1 exit status

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In the C++ programming language, you can define a struct just like you define a class. The reason you’re getting the error is because you haven’t defined the methods strictly.

#include <iostream>

using namespace std;

struct Date
{
    /* fields */
    int _year, _month, _day;
    
    /* constructor */
    Date(int year, int month, int day) : _year(year), _month(month), _day(day){}
    
    /* setter method */
    void add_day(int n)
    {
        /* You need to develop an algorithm to keep track of the end of the month and the year. */
        _day += n;
    }
    
    /* getter method */
    int get_day()
    {
        return _day;
    }
};

int main()
{
    Date today(2021, 1, 6);
    today.add_day(1);
    cout << today.get_day() << endl;
    return 0;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading