0

I'm currently reading a c++ book, and I have a few questions.

1) Is void only used to declare a return type in this example?

2) If void causes it NOT to return data to the calling function, why is it still displaying the message "Welcome to the Grade Book!"?

3) Isn't it easier to create a simple function instead of making an object?

#include <iostream>
using namespace std;

class GradeBook
{
public:
    void displayMessage()
    {
        cout << "Welcome to the Grade Book!" << endl;
    }
};

int main()
{
    GradeBook myGradeBook;
    myGradeBook.displayMessage();
}
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
Seb
  • 1,966
  • 2
  • 17
  • 32

3 Answers3

5
  1. That's the only use in this example. You can also have pointers to void (void *).
  2. You're not returning that message. You're printing it. In C++, methods and functions can have side effects. One possible side effect is output.
  3. Yes, in this case. However, this is not a realistic example of the benefits of objects. For that, see How do I describe Object-Oriented Programing to a beginner? Is there a good real-world analogy? among many places.
Community
  • 1
  • 1
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
1

Is void only used to declare a return type in this example?

Yes, it indicates that displayMessage() will not return back anything to it's caller.
It can also be used as a void *, i.e: A generic pointer which can point to anything, but it is not being used in that way in your example.

If void causes it NOT to return data to the calling function, why is it still displaying the message "Welcome to the Grade Book!"?

The message is not returned to the caller of the function, the message is directed to the standard output when the control was in the function and executing that particular statement.

Isn't it easier to create a simple function instead of making an object?

It's not a matter of ease. It is more of an matter of Object Oriented design principles.
The purpose of having classes and member functions is to bind together the data and the methods that operate on that data in a single unit. You might want to pick up a good book and read up Encapsulation & Abstraction.

The Definitive C++ Book Guide and List

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
0
  1. In your case the function "displayMeassage" is not returning the string, it is just printing your message.

  2. Returning means, suppose an example:

    class A

    {

      int num=0;
    
      int getNum()
    
      {
    
         return num;
    
      }
    

    };

    void main()

    {

       A a;
    
       int no=a.getNum();
    
       cout<<"no : "<<no;
    

    }

    In above example, then way getNum is returning the number that is what returning is
    called.

  3. Whatever you are taking the example is not good to understand the return concept.

Thanks

Bhavesh Shah
  • 3,299
  • 11
  • 49
  • 73