I am reading a book "C++ How to Program(8th edition)",downloaded it from The Pirate Bay.
Atm I on third chapter "Introduction to Classes,Objects and Strings".
Can u plz help me in understanding C++ classes been stucked on it for 5 days already.
//creates a GradeBook class
//function that sets the course name
void setCourseName( string name )
courseName = name; //assigns name to data member course name (object)
} // end function setCourseName
//function that gets the course name
return courseName; //return the object's course name
} //end function get course name
//function that displays a welcome message
//this statement calls getCourseName to get the
//name of the course this GradeBook represents
cout << "Welcome to the grade book for\n" << getCourseName() << "!" << endl;
} //end function displayMessage
string courseName; //course name for this GradeBook
}; //end class GradeBook
//function main begins program execution
string nameOfCourse; //string of characthers to store the course name
GradeBook myGradeBook; //create a GradeBook object named myGradeBook
//display initial value of courseName
cout << "\nPlease enter the course name: " << endl;
getline( cin, nameOfCourse); //read a course name with blanks
myGradeBook.setCourseName( nameOfCourse); // set the course name
cout << endl; //outputs a blank line
myGradeBook.displayMessage(); //display message with new course name
cout << endl;
} //ends main
In the setCourseName function what is the
courseName = name;
supposed to do.
In the getCourseName function
what value is it returning
Anyway I do not understand this code at all,its so confusing.
It would be nice if u could explain it. :D
The class has one member: it's a std::string called courseName; You see it's defined on line 30.
This member is private, so only functions inside of the class can use it. If you are outside of the class, you need another function to get or set it. These are called "getters" and "setters" as described below.
In setCourseName, you add a string as an argument. That argument becomes the string "name". Your private member courseName is then set to name. THis is commonly called a setter because it serves no other purpose than to set the private member.
In getCourseName, you can get the value of the courseName private member. This kind of function is commonly galled a getter because it serves no other purpose than to output the private member.
A class with only a member (like courseName), a setter (like setCourseName) and a getter (like getCourseName) is rather useless. You could have just used a std::string instead. However, as soon as you start having other functions involved that do things with the private member, it becomes very useful as you want to limit access to this private member only to member functions.