Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

void displayMessage() const { ... } a question about const being used

13 views
Skip to first unread message

G G

unread,
Jun 16, 2019, 4:04:38 PM6/16/19
to
from deitel and deitel C++ how to prrogram
9th edition


// Fig. 3.1: fig03_01.cpp
// Define class GradeBook with a member function displayMessage()
// create a GradeBook object, and call its displayMessage()

#include <iostream>

using namespace std;


// GradeBook class definition
class GradeBook
I
public:
// function that displays a welcome message to the GradeBook user
void displayMessage() const
{
cout << "Welcome to the Grade Book!" << ends;
}
];


// function main begins program execution
int main()
{
GradeBook myGradeBook;

myGradeBook.displayMessage();
}


My question is about the const use after
displayMessage(). The author notes it should be
used to indicate the function will not change the object
GradeBook. Could you please explain. i'm trying to
understand why it would be necessary, along with
when it would be used again in a program.

Szyk Cech

unread,
Jun 16, 2019, 4:15:56 PM6/16/19
to
> My question is about the const use after
> displayMessage(). The author notes it should be
> used to indicate the function will not change the object
> GradeBook. Could you please explain. i'm trying to
> understand why it would be necessary, along with
> when it would be used again in a program.

This const will protect you from accident modify GradeBook
object when you implement function GradeBook::displayMessage()
It also tell to class users that it will not modify class.
It can be usefull for testers or programmers from your team.

Manfred

unread,
Jun 16, 2019, 4:48:27 PM6/16/19
to
One possible source of confusion in the example is that the class
GradeBook does not have any state, so it is not evident that
displayMessage() does not change it, since it does not have any.
Suppose you have some state (e.g. member variables) that is modified by
some other member function, then the use for the 'const' qualifier
becomes evident (and it is very useful too)

Moreover, if you declare the object as:
const GradeBook myGradeBook;

then the compiler will prevent invocation of non-const methods on it.

G G

unread,
Jun 16, 2019, 5:23:10 PM6/16/19
to

>
> One possible source of confusion in the example is that the class
> GradeBook does not have any state, so it is not evident that
> displayMessage() does not change it, since it does not have any.
> Suppose you have some state (e.g. member variables) that is modified by
> some other member function, then the use for the 'const' qualifier
> becomes evident (and it is very useful too)
>
> Moreover, if you declare the object as:
> const GradeBook myGradeBook;
>
> then the compiler will prevent invocation of non-const methods on it.


Thanks.
0 new messages