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

>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;
}

Leave a Reply