C++ Class objects

Hello, I don't know how to explain the problem and how to solve it, please see if you can.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
  #include <iostream>
#include <string>
using namespace std;






class GradeBook
{
public:
    GradeBook(string name)
    {
        setCourseName(name);
    }
    //sets course name...
    void setCourseName(string name)
    {
        courseName = name; //stores the name in object
    }

    //gets the course name
    string getCourseName()
    {
        return courseName; //return the object course name
    }

    // displays welcome message
    void displayMessage()
    {
        //calls getCourseName()
        //to display the message along with the course name
        cout<<"Welcome to the grade book for " << getCourseName() << endl;
        //
    }

private:
    string courseName;
};


int main()
{
    GradeBook gradeBook1("CS1 Intro to C++");
    GradeBook gradeBook2("CS2 Data structure");
    string nameOfCourse;
    GradeBook myGradeBook;

    //display initial value for courseName
    cout<<"initial course name is: " <<myGradeBook.getCourseName()<<endl;
    //

    //prompt for input the course name
    cout<<endl<<"Please enter course name :"<<endl;
    getline(cin,nameOfCourse);
    myGradeBook.setCourseName(nameOfCourse);

    cout<<endl;
    myGradeBook.displayMessage();
}
You create an object for the class "GradeBook" you then try to retrieve the string variable "courseName" that was never initialized. That might be your problem, so just either use the constructor you made and input a course name or set the course name before getting it.

EDIT: You can also make a constructor with no parameters and set a default value to the variable "courseName"
Last edited on
Hello, I don't know how to explain the problem and how to solve it, please see if you can.
Now, if that isn't precise...

Your problem is on line 48: Either you create a second constructor that takes no parameter or you provide a default parameter for your existing constructor on line 13, like so:
1
2
3
4
    GradeBook(string name = "")
    {
        setCourseName(name);
    }
Thank you.
Topic archived. No new replies allowed.