In this tutorial we are going to study about
- Constant Member Functions
- Mutable Keyword
- Overloading Member Functions
1. Constant Member Functions in C++
Below are few points on Constant Member Functions
- “const” is the keyword to declare a constant member function.
- Once the member function is declared as constant, it cannot modify the data member value in that function.
- We use this in the functions, where we don’t need accidental modification of the data.
Example:
#include <iostream> using namespace std; class MyClass { int num; public: void myFunc() const { // error: cannot assign to non-static data member within const member function 'myFunc //num ++; cout<<"In const function"<<endl; } }; int main(void) { static MyClass obj; obj.myFunc(); return 0; }
Output:
In const function
2. Mutable data members in C++
Below are few points on “mutable” keyword.
- “mutable” keyword is only applicable to data members.
- In some cases, we need to modify a data inside a constant member functions.
- In such cases, we make a data member as mutable, so that it can be modified inside a constant member function.
Example:
#include <iostream> using namespace std; class MyClass { mutable int iNum; int num; public: void myFunc() const { // error: cannot assign to non-static data member within const member function 'myFunc //num ++; iNum++; // no error cout<<"In const function"<<endl; } }; int main(void) { static MyClass obj; obj.myFunc(); return 0; }
Output:
In const function
3. Overloading Member Functions in C++
- Function overloading is a feature two or more functions having same name but different parameters.
- This is kind of polymorphism feature of C++
Example:
#include <iostream> using namespace std; void fun(int num) { cout<<"Int function"<<endl; } void fun(double num) { cout<<"double function"<<endl; } void fun(string num) { cout<<"String function"<<endl; } int main(void) { fun(10); fun(12.34); fun("String"); return 0; }
Output:
Int function double function String function