Just started coding in C++. I want to understand how class of C++ works when I want to define a variable and put it out with a different name.
Apologies if the question doesn't make sense. The code I have is from a well-known textbook. I'm not getting any error messages; I'm just trying to understand how works in C++. I have some experience in Python and this process confused me.
#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 );
}
The output comes out fine.
Notice two variables: courseName and nameOfCourse. The textbook says that courseName variable transformed into nameOfCourse variable on line 17, where it goes:
string nameOfCourse;
Can you help me understand how this transformation occurs?
If courseName was a reference (std::string&) then it would be correct to say that in line 17, courseName is bound to nameOfCourse (in other words, for the duration of that displayMessage call, courseName would be just another name for nameOfCourse).
But 1. that is called "reference binding", not "variable transformation", and 2. that's not what is happening here - nameOfCourse is copied to courseName when displayMessage is called: The copy constructor of std::string is used to create a copy of nameOfCourse.
Variables (and/or variable names) are not "transformed" in C++ (especially not in the context of calling by value), so unless there is a translation/transcription/general communication problem interfering here, the book is simply wrong.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With