Home    About me    Publications    Blog    Undergrad memories

Fabio Ruini’s blog

Because Italians do it better! What the f**k? Ehm… the blogs, I mean… obviously! :-/

How to use classes in C++ (lesson #2)

In this second lesson, we will see how to pass a parameter from the main program to a member function. In more details, we want to be able to ask the user for the course name and then print it on the screen through displayMessage member function.


[line 01]  #include < iostream >
[line 02]  using std::cout;
[line 03]  using std::cin;
[line 04]  using std::endl;

[line 05]  #include < string >
[line 06]  using std::string;
[line 07]  using std::getline;

[line 08]  class GradeBook {
[line 09]    public:
[line 10]      void displayMessage(string courseName) {
[line 11]	  	cout << "Welcome to the grade book for\n" <<
		  	courseName << “!” << endl;
[line 12]	     }
[line 13]  };

[line 14] int main() {
[line 15]    string nameOfCourse;
[line 15]    GradeBook myGradeBook;

[line 16]    cout << “Please enter the course name:” << endl;
[line 17]    getline(cin,nameOfCourse);

[line 18]    myGradeBook.displayMessage(nameOfCourse);
[line 19]    return 0;
[line 20] }

The procedure is very easy.

In the main function, we first declare a string variable called nameOfCourse (line 15) and then we prompt the user with a “Please enter the course name” question (line 16). The answer will be stored in the just defined variable (line 17).

Then we call the displayMessage function (line 18), passing to it nameOfCourse. In fact, the member function, as defined at line 10, is now able to receive an input parameter (a string). The value stored in this parameter, called courseName inside the function, will be displayed on the user’s screen, prefixed by the string: “Welcome to the grade book for ” (line 11).

Non ci sono ancora commenti. Vuoi essere il primo?

Lascia un commento