Const functions?

Hello, what's the difference between
1
2
3
4
class myclass
{
int fx(int); //const not used here
};

and
1
2
3
4
class myclass
{
int fx(int) const; // const!?
};

So how const functions are different from non-const functions? When const is required and when not?
Thanks for help.
Const is required when you have a value that will remain the same throughout your entire program.

the value of PI for example is usually set to a const because PI is something that shouldn't change when calculating things that need PI.
Also check this out:

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <cstdlib>
#include <iostream>
using namespace std;

class MyInt
{
    public:
    MyInt(int n):val(n){}
    ~MyInt(){}
    
    //set() is not guaranteed not to change the calling object
    //thus a const object can't call set()
    void set(int n) {val=n;}
    
    //get() is guaranteed not to change the calling object
    //thus it can be called from both const and non-const objects
    int get() const {return val;}
    
    private:
    int val;
};

int main()
{
    MyInt my_int(10);
    const MyInt my_const_int(20);
    
    cout << "my_int: " << my_int.get() << endl;
    cout << "my_const_int: " << my_const_int.get() << endl;
    
    my_int.set(5);
    cout << "my_int: " << my_int.get() << endl;
    
    //removing "//" from the next line will result in a compilation error
    //my_const_int.set(5);
    cout << "my_const_int: " << my_const_int.get() << endl;
        
    system("pause");
    return 0;
}
Last edited on
Constant methods are methods that logically do not alter the state of the object. In the simple case, the method "promises" not to modify any of the members.

Another common example for this is: if you dereference a const_iterator to an object, you can only call constant methods. If you have a [regular] iterator to an object, you can call any methods.

Last edited on
Topic archived. No new replies allowed.