TookieWookie
TookieWookie

Reputation: 382

Error: "No matching function for call to Date::Date()"

I tried to implement the constructor for the Person class (see code at the end of the post). Codeblocks gives this error for line 37 (i.e. const Date &date)):

error: no matching function for call to 'Date::Date()'

Why is the constructor for Date being called? How do I fix the error?

class Date
{
    public:
        Date(int day, int month, int year);
        int GetYear() const;
    private:
        int Day;
        int Month;
        int Year;
};

Date::Date(int day, int month, int year){

    Day = day;
    Month = month;
    Year = year;
}

class Person
{
    public:
        Person(const string &name, const string &address, const Date &date);
        string GetAddress() const;
        string GetName() const;
    private:
        string Name;
        string Address;
        Date DateOfBirth;
};

Person::Person(const string &name,
               const string &address,
               const Date &date)
{
    Name = name;
    Address = address;
    DateOfBirth = date;
}

Upvotes: 0

Views: 862

Answers (1)

molbdnilo
molbdnilo

Reputation: 66371

It is called because members are initialized before the constructor body is entered - in your Person constructor, you are assigning to the members, not initializing them.
Since you're not explicitly initializing the members, they are default-initialized first.

Use the initializer list for initialization:

Person::Person(const string &name,
               const string &address,
               const Date &date)
    : Name(name),
      Address(address),
      DateOfBirth(date)
{
    // Nothing needs to be done here.
}

Upvotes: 6

Related Questions