Let's break apart this code to understand what it's doing:
#include <iostream>
#include <string> //program uses C++ standard string class
using namespace std;
// Gradebook class definition
class GradeBook
public:
void displayMessage( string courseName )
{
cout << "Welcome to the Grade Book for\n" << courseName << "!"
<< endl;
}
};
int main()
{
string nameOfCourse;
GradeBook myGradeBook;
// prompt for and input course name
cout << "Please enter the course name: " << endl;
getline( cin, nameOfCourse );
cout << endl;
myGradeBook.displayMessage( nameOfCourse );
}
Starting in the main()
method, when your program runs the following things happen:
int main()
{
string nameOfCourse;
At this point, the program has begun, and it's initialized a variable of type string
. This invokes the default constructor for string
, which creates a string with size 0 (so an empty string).
In order to create the string, the program allocates space for the string on the program's stack. This space is what the default constructor uses when initializing the string.
Once the program is running, the names chosen for the variables don't matter at all, and nowhere does it keep track of what you named a variable.
GradeBook myGradeBook;
Here, you declare that a GradeBook
object exists. Because GradeBook
is empty, in an optimized program nothing actually happens. It's never "created", because there's nothing to create. The compiler might direct the program to assign GradeBook
an address based on the current stack location, but because your code doesn't use the address of myGradeBook
anywhere, that might not happen, either.
cout << "Please enter the course name: " << endl;
The first part (cout << "Please enter the course name: "
) sends that message to standard output. The << endl
portion adds a newline, and flushes the buffer used by standard output. endl
is actually a function, and so this would be equivalent to writing endl(cout << "Please enter the course name: ")
.
getline(cin, nameOfCourse);
This reads data from standard input until the line ends. It puts that data in nameOfCourse
. In order to put that data in nameOfCourse
, the program modifies the memory location it assigned to nameOfCourse
by calling the appropriate string
member functions (probably the append
member function, which appends text to a string).
cout << endl;
Adds a newline and flushes the buffer again.
myGradeBook.displayMessage( nameOfCourse );
The following things happen in order to call displayMessage
:
- If there's any data in the registers, the program saves it to the stack (so that the registers are freed up)
- The program makes space on the stack for courseName
- The program calls the string
type's copy constructor, creating a new string in the space allocated for courseName
- The program jumps to the location where the machine code for displayMessage
begins
- displayMessage
runs
- displayMessage
returns
- the main()
method resumes
At that point, the program exits because there's nothing else to do.