What does this mean!!

From my book:

"A const member function cannot call a non-const member function of the same class, since this would potentially modify the object."

Can anyone give an example of this? If it is declared a const class how any member function even be called if it isn't declared const? I am really confused. Could someone please help me at what exactly this means. I know about why it needs to be const because of the 'this' pointer but I don't understand this.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

class MyNum
{
public:
    MyNum(int n) : _num(n) {}


    void setNum(int n) { _num = n ; }

    int getNum() const          // shouldn't change any member variables, therefore it is const
    { 
        // setNum(5);              // illegal here.  Can't call a non-const member from a const member.
        return _num ; 
    }  

private:
    int _num ;
};

int main()
{
    MyNum num(10) ;
    std::cout << num.getNum() << '\n' ;
}
Oooh ok, so just to make sure that no function at all modifies anything? Thanks!
Also even it wasn't a non-const function it would be impossible to modify cause of the 'this' pointer that is const. You know what I mean right?

Full names of any object of the class are: this->blahblah. Since this is const it would be impossible anyway right but the compiler just wants to make sure and wont let anything call any function that does not assume this.

Also cant you just use a pointer to modify any of the values without anything going wrong?
Can someone please help!
You can *pretend* that the this point has this type normally:

MyClass *const this;

And you can *pretend* that the this pointer has this type in a const member function:

MyClass const *const this;

Reminder: "const" applies to whatever is on its left.
LB

Can you quickly explain the const thing for const member functions except in a little more detail? Thanks!


Also thanks for that small example, really helps.
Last edited on
closed account (zb0S216C)
Read the last paragraph of this post: http://www.cplusplus.com/forum/beginner/92036/#msg494740

Wazzak
Last edited on
Ok thanks :D
Topic archived. No new replies allowed.