1

I'm trying to initialize Date, maybe I forgot something about it. 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 which I don't know how to fix it probably:

undefined reference to `Date::Date(int, int, int)'
collect2.exe: error: ld returned 1 exit status
Tien Hung
  • 139
  • 8
  • 1
    You have *declared* what the `Date` struct looks like, but where are the *definitions* (ie, the *implementations*) of its methods? The linker can't find them (because you didn't write code for them, or didn't add that code to the project), that is what the error is complaining about. – Remy Lebeau Jan 07 '22 at 02:05

1 Answers1

3

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;
}
Sercan
  • 4,739
  • 3
  • 17
  • 36