CaSdm
CaSdm

Reputation: 27

How to write a constructor for a class who includes another class?

I write a 'Student' class which has two classes called 'Course' and 'Score' as its members.
Now I write a constructor for initialization of 'Student' class and get these errors:
1.missing default argument on parameter 'e'
2.no matching constructor for initialization of 'Student'
3.candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided for class Student

update: After change the class, now I find the problem is in my main function, how to solve this? I give the errors and warnings in the picture.

#include <iostream>
#include <string>
using namespace std;
class Course
{
    friend void readCourse(Course &scourse);
public:
    Course(Course &scourse) : cno(scourse.cno), cname(scourse.cname) { }
    Course(const string &a, const string &b) : cno(a), cname(b) { }
    void course_show();
private:
    string cno;
    string cname;
};
class Score
{
    friend void readScore(Score &sscore);
public:
    Score(Score &sscore) : score(sscore.score) { }
    Score(int a) : score(a) { }                                                                                                                                                                                          
    void score_show();
private:
    int score;
};
class Student
{
    friend void readStudent(Student &student);
public:
    Student(const string a = "", const string b = "", const string c = "", const string d = "",
        Course e, Score f) : sno(a), sname(b), gender(c), grade(d),
            scourse(e), sscore(f) { }
    void student_show();
private:
    string sno;
    string sname;
    string gender;
    string grade;
    Course scourse;
    Score sscore;
};

int main()
{
    Student s1;
    Student s2;
    readStudent(s1);
    readStudent(s2);
    s1.student_show();
    s2.student_show();
    return 0;
}

errors and warnings

Upvotes: 1

Views: 161

Answers (2)

Destructor
Destructor

Reputation: 523

Default parameters should be moved to the end of the argument list.

Student(const string a = "", const string b = "", const string c = "", const string d = "", Course e, Score f)

The above must be corrected as,

Student(Course e, Score f, const string a = "", const string b = "", const string c = "", const string d = "")

Upvotes: 1

CinCout
CinCout

Reputation: 9619

Parameters with default values should always be placed at the end of the parameter list.

Hence,

Student(const string a = "", const string b = "", const string c = "", const string d = "",
        Course e, Score f)

should be

Student(Course e, Score f, const string a = "", const string b = "", const string c = "", const string d = "")

Upvotes: 3

Related Questions