Quick question learning OOP. Const or no const in the function prototype?

Hey guys I've got a quick question I hope someone could help me answer. My computer science class has started in the topic of object oriented programming and my teacher writes his code a little differently then the code the author of my text book writes.

I noticed in class that my professor would write a class member function like this

1
2
3
4
5
class Test
{
public:
void PrintMe() const;
}


Whereas my book would write something similar like this

1
2
3
4
5
class Test
{
public:
void PrintMe (void);
}


The above way is how the author writes all of the member function examples. I never see the word CONST in any member functions yet my teacher constantly uses it in his member functions. Are the two ways the same? If anyone could clarify this for me I'd greatly appreciate it.
A member function with a trailing const means that function promises not to modify the object it is invoked on. You should use it as much as possible to indicate the same.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class TestConst
{
public:
    void PrintMe() const ;
};

class Test
{
public:
    void PrintMe() ;
};

int main()
{
    const TestConst tc ;
    tc.PrintMe() ;   // no error

    const Test t ;
    t.PrintMe() ;    // error, t is const.
}


Googling const correctness may prove instructive.
Using const in a member function prototype means, the function would not be changing any member variable. That is why it's normally used with printout functions.

Aceix.
cire and Aseix have pretty much nailed it.

It's something that a lot of programmers forget to do, so kudos to your teacher for doing it properly.
The "void" in the parameter list comes from C.
You shouldn't use it in C++.
Topic archived. No new replies allowed.