Meaning of 'const' last in a function declaration of a C++ class?


Sometimes we can find the keyword ‘const’ present at the last of function declaration. So what does it mean?

Using this one function can be made as constant. The idea of constant function is that, the function cannot be modified from the objects, where they are called. It is recommended to use the constant functions in our program.

Let us see one example of constant function.

Example

#include<iostream>
using namespace std;
class MyClass {
   int value;
   public:
      MyClass(int val = 0) {
         value = val;
      }
      int getVal() const {
         //value = 10; [This line will generate compile time error as the function is constant]
         return value;
      }
};

Output

The value is: 80

Now we will see another important point related to constant functions. The constant functions can be called from any type of objects, as you have seen from the above example. But some non-constant functions cannot be called from constant objects.

Example

#include<iostream>
using namespace std;
class MyClass {
   int value;
   public:
      MyClass(int val = 0) {
         value = val;
      }
      int getVal(){
         return value;
      }
};
main() {
   const MyClass ob(80);
   cout<< "The value is: " << ob.getVal();
}

Output

[Error] passing 'const MyClass' as 'this' argument of 'int
MyClass::getVal()' discards qualifiers [-fpermissive]

Advertisements