Function overloading and const keyword in C++


In C++, we can overload functions. Some functions are normal functions; some are constant type functions. Let us see one program and its output to get the idea about the constant functions and normal functions.

Example

#include <iostream>
using namespace std;
class my_class {
   public:
      void my_func() const {
         cout << "Calling the constant function" << endl;
      }
      void my_func() {
         cout << "Calling the normal function" << endl;
      }
};
int main() {
   my_class obj;
   const my_class obj_c;
   obj.my_func();
   obj_c.my_func();
}

Output

Calling the normal function
Calling the constant function

Here we can see that the normal function is called when the object is normal. When the object is constant, then the constant functions are called.

If two overloaded method contains parameters, and one parameter is normal, another is constant, then this will generate error.

Example

#include <iostream>
using namespace std;
class my_class {
   public:
      void my_func(const int x) {
         cout << "Calling the function with constant x" << endl;
      }
      void my_func(int x){
         cout << "Calling the function with x" << endl;
      }
};
int main() {
   my_class obj;
   obj.my_func(10);
}

Output

[Error] 'void my_class::my_func(int)' cannot be overloaded
[Error] with 'void my_class::my_func(int)'

But if the arguments are reference or pointer type, then it will not generate error.

Example

#include <iostream>
using namespace std;
class my_class {
   public:
      void my_func(const int *x) {
         cout << "Calling the function with constant x" << endl;
      }
      void my_func(int *x) {
         cout << "Calling the function with x" << endl;
      }
};
int main() {
   my_class obj;
   int x = 10;
   obj.my_func(&x);
}

Output

Calling the function with x

Updated on: 30-Jul-2019

344 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements