Extra const after function implementation...

when the word 'const' is placed after a function definition, what does it mean. eg: int func(int& a) const {}
Last edited on
A method/member function that is declared const is "read-only" and can not modify the object's data members.

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
class Foo {
     private:
         int a;
     public:  
         int getA(void) const { a = 5; return a; }
         Foo(const int at): a(at) { } 
};

int main(void) {
    Foo a(5);
    std::cout << a.getA() << std::endl;
    return 0;
}

The member function/method getA() tried to modify the data member a, but it's read-only so the compiler threw back an error. The code would compile if we were to remove the 'const' keyword.
Last edited on
Topic archived. No new replies allowed.