-6

So I have been self studying C++ and I've come across a concept that I don't entirely understand. It's mainly dealing with how the function parameter interacts with the main block.

#include <iostream>
#include <string>
using namespace std;

class GradeBook
{
public:
    void displayMessage(string courseName)
    {
        cout << "Welcome to the gradebook for " << courseName <<endl;
    }
};

int main()
{
   string nameOfCourse;

   GradeBook myGradeBook;
   cout <<"Please enter the course name:" <<endl;
   getline(cin, nameOfCourse);
   myGradeBook.displayMessage(nameOfCourse);

You make a function with a string parameter with the name being coursename. You then look at the last line of code. 'myGradeBook.displayMessage(nameOfCourse); And the program knows that you're talking about the courseName variable. How is this possible since they are two different variables. I understand that you're using the mygradebook object to access the displaymessage but the parameter of nameOfCourse confuses me. How does it tie in with the gradebook function class? Thank you for the help should you look this over.

Drai
  • 1
  • 3
  • 5
    Nothing to do with `class`es. You don't understand functions. – LogicStuff Jul 11 '17 at 18:38
  • 5
    Sounds like you could use a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver Jul 11 '17 at 18:38
  • 3
    When the function is called, the value of `nameOfCourse` is copied into `courseName`. It's called *pass by value*. It seems you should think about getting [a good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Some programmer dude Jul 11 '17 at 18:39
  • Thank you for that explanation. I'm going to look up pass by value and I'll be following up on the book suggestion. Thank you all for your help. – Drai Jul 11 '17 at 18:53

1 Answers1

1

And the program knows that you're talking about the courseName variable. How is this possible since they are two different variables

One was copied into the other, by virtue of passing it to a function.

This is how functions work. Consult the first couple of chapters of your C++ book for more info.

How does it tie in with the gradebook function class?

It doesn't, at all. You simply passed a function argument.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055