
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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