0

I have created a constructor, but why there is still have an error "no default constructor exists for class"? I have searched for the answer to the question, but I am still not clear about this error. Can someone help me?

pragma once
#include<string>
using namespace std;
class Date
{
private:
    int month;
    int day;
    int year;
public:
    Date(int newmonth, int newday, int newyear)
    {
        month = newmonth;
        day = newday;
        year = newyear;
    }
};
class Student
{
private:
    string name;
    Date birthDay;
    int score;
public:
    Student(string newname, Date newbirthDay, int score)
    {

    }
};
timeil0611
  • 39
  • 1
  • 1
  • 7

2 Answers2

1

In Student, you need to initialize the Date birthDay variable as part of the constructor's initialization list, otherwise it will attempt to initialize it with the default constructor, which does not exist. Example:

Student(string newname, Date newbirthDay, int score) : name(newname), birthDay(newbirthDay), score(score) {
}

In general, you should be using the initialization list (same for your Date class).

On an unrelated note, you should consider passing objects in by const &, i.e.:

Student(const string &newname, const Date &newbirthDay, int score) : name(newname), birthDay(newbirthDay), score(score) {
}
ChrisMM
  • 8,448
  • 13
  • 29
  • 48
0

A default constructor needs an empty parameter list, so in your case it'd be Date() or Student()

Ryan
  • 169
  • 8