Cpp Tutorial: Constant member functions and Overloading Member Functions, Mutable in C++

In this tutorial we are going to study about
1. Constant Member Functions
2. Mutable Keyword
3. Overloading Member Functions

1. Constant Member Functions in C++

Below are few points on Constant Member Functions
1. “const” is the keyword to declare a constant member function.
2. Once the member function is declared as constant, it cannot modify the data member value in that function.
3. 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.
1. “mutable” keyword is only applicable to data members.
2. In some cases, we need to modify a data inside a constant member functions.
3. 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++

1. Function overloading is a feature two or more functions having same name but different parameters.
2. 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
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *